我试图通过反射获取静态私有属性的值,但失败并出现错误。
Class class = home.Student.class;
Field field = studentClass.getDeclaredField("nstance");
Object obj = field.get(null);
我得到的例外是:
java.lang.IllegalAccessException: Class com.test.ReflectionTest can not access a member of class home.Student with modifiers "private static".
此外,我需要调用一个private,代码如下。
Method method = studentClass.getMethod("addMarks");
method.invoke(studentClass.newInstance(), 1);
但问题是Student类是一个单独的类,是私有的构造函数,不能访问。
您可以设置可访问的字段:
field.setAccessible(true);
是的。您必须使用AccesibleObject中定义的setAccessible(true)
来设置它们的可访问性,该对象是Field
和Method
的超类
对于静态字段,您应该能够做到:
Class class = home.Student.class;
Field field = studentClass.getDeclaredField("nstance");
field.setAccessible(true); // suppress Java access checking
Object obj = field.get(null); // as the field is a static field
// the instance parameter is ignored
// and may be null.
field.setAccesible(false); // continue to use Java access checking
和私人方法
Method method = studentClass.getMethod("addMarks");
method.setAccessible(true); // exactly the same as with the field
method.invoke(studentClass.newInstance(), 1);
还有一个私人构造函数:
Constructor constructor = studentClass.getDeclaredConstructor(param, types);
constructor.setAccessible(true);
constructor.newInstance(param, values);
是的,你可以这样"作弊":
Field somePrivateField = SomeClass.class.getDeclaredField("somePrivateFieldName");
somePrivateField.setAccessible(true); // Subvert the declared "private" visibility
Object fieldValue = somePrivateField.get(someInstance);