java 反射 类的带参数实例化

2024-12-12 23:54:12
推荐回答(1个)
回答1:

把参数里面的int改成Integer public Person(String name, Integer age) 这种
/**
* 得到带构造的类的实例
* */
public static Object newInstance(String className, Object[] args) throws Exception {
Class newoneClass = Class.forName(className);
Class[] argsClass = new Class[args.length];
for (int i = 0, j = args.length; i < j; i++) {
argsClass[i] = args[i].getClass();
}
Constructor cons = newoneClass.getConstructor(argsClass);
return cons.newInstance(args);
}