注意:int.class不等于Integer.class
问题:因此此处调用Person p = createPerson(Person.class,3,"nilu");会找不到对应构造函数,因为它找的是传入Integer与String的构造函数,如何解决?
//junit测试函数
@Test
public 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);
这一行 根据_args是哪些.class 会决定得到哪个构造函数,这里实际得到的是Integer.class与String.class;
然而Person(int age, String name)实际要的是int.class与String.class;
这是由于调用createPerson时候,3这个int被自动装箱了,变成了Integer,因此程序会报错提示味找到构造函数createPerson(Integer,String)
PIPIONE
慕侠2389804
相关分类