注意:int.class不等于Integer.class 問題:因此此處調(diào)用Person p = createPerson(Person.class,3,"nilu");會找不到對應(yīng)構(gòu)造函數(shù),因為它找的是傳入Integer與String的構(gòu)造函數(shù),如何解決?//junit測試函數(shù)@Testpublic void test() throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {Person p = createPerson(Person.class,3,"nilu");p.eat();}public <T> T createPerson(Class<T> clazz, Object ...args) throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {final List<Class> list = new ArrayList<Class>();for(Object obj : args) {list.add(obj.getClass());}Class []_args = new Class[args.length];list.toArray(_args);list.clear();Constructor<T> constructor = clazz.getConstructor(_args);T t = constructor.newInstance(args);return t;}類:public class Person {private String name;private int age;public Person() {this.age = 18;this.name = "default name";System.out.println("Person constructor");}public Person(String name) {this.name = name;System.out.println("Person name : " + name);}public Person(int age, String name) {this.age = age;this.name = name;System.out.println("Person name : " + name);System.out.println("Person age : " + age);}}=======================================================================問題描述補充:Constructor<T> constructor = clazz.getConstructor(_args);這一行 根據(jù)_args是哪些.class 會決定得到哪個構(gòu)造函數(shù),這里實際得到的是Integer.class與String.class;然而Person(int age, String name)實際要的是int.class與String.class;這是由于調(diào)用createPerson時候,3這個int被自動裝箱了,變成了Integer,因此程序會報錯提示味找到構(gòu)造函數(shù)createPerson(Integer,String)
希望自定義一個函數(shù),傳入類.class與可變參數(shù),返回通過反射調(diào)用對應(yīng)構(gòu)造函數(shù)構(gòu)造出的類
慕的地6264312
2023-04-09 10:06:08