-2 java reflection parameterized-types
我明明把构造函数的setAccessible设置为true了,可是为什么还是报错!你能告诉我如何修复它吗
public class Person {
// fields...
private Person(String name, int age, String address, int num) {
this.name = name;
this.age = age;
this.address = address;
this.num = num;
System.out.println("private full-constructor be created");
}
}
Run Code Online (Sandbox Code Playgroud)
// 发生错误?!为什么?
public static void operatePrivateConstructorFullParameter(Class<? extends Person> clzz) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Constructor<? extends Person> constructor = clzz.getConstructor(String.class, int.class, String.class, int.class);
constructor.setAccessible(true);
Person person = constructor.newInstance("Miao", 18, "MOON", 88);
}
public static void main(String[] args) throws Exception {
Class<? extends Person> clzz = Person.class;
operatePrivateConstructorFullParameter(clzz);
}
Run Code Online (Sandbox Code Playgroud)
此错误与可访问性无关,而是与查找构造函数有关。
正如其记录的合同中所指定的,该方法Class.getConstructor()只会查找公共构造函数。
如果你想找到这个私有构造函数,你需要使用getDeclaredConstructor()正确的参数类型
找到构造函数后,您仍然需要使其可访问。但请注意,在模块化应用程序中,封装可能会阻止您以这种方式使用反射。