我试图通过反射获取静态私有属性的值,但它失败并出现错误。
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".
此外,我需要使用以下代码调用私有。
Method method = studentClass.getMethod("addMarks");
method.invoke(studentClass.newInstance(), 1);
但问题是Student类是单例类,而构造函数是私有的,无法访问。
答案 0 :(得分:67)
您可以设置可访问的字段:
field.setAccessible(true);
答案 1 :(得分:13)
是的。您必须使用setAccessible(true)
中定义的AccesibleObject来设置它们,Field
是Method
和{{3}}
使用静态字段,您应该能够:
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);
答案 2 :(得分:1)
是的,你可以这样“欺骗”:
Field somePrivateField = SomeClass.class.getDeclaredField("somePrivateFieldName");
somePrivateField.setAccessible(true); // Subvert the declared "private" visibility
Object fieldValue = somePrivateField.get(someInstance);