猿问

希望自定义一个函数,传入类.class与可变参数,返回通过反射调用对应构造函数构造出的类

注意: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)

慕的地6264312
浏览 135回答 2
2回答

PIPIONE

循环取参数class的时候判断一下是否基本类型,如果是就先转成基本类型的class。或者判断下这个类是否有个TYPE常量:Class&nbsp;cls&nbsp;=&nbsp;obj.getClass();Field&nbsp;f&nbsp;=&nbsp;cls.getDeclaredField("TYPE");if&nbsp;(f&nbsp;!=&nbsp;null)&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;list.add((Class)&nbsp;f.get(null));}&nbsp;else&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;list.add(cls);}

慕侠2389804

参数类型不一致,自动装箱,自动拆箱先不要考虑试试。
随时随地看视频慕课网APP

相关分类

Java
我要回答