是否可以通过反射调用私有属性或方法

M.J*_*.J. 40 java reflection

我试图通过反射获取静态私有属性的值,但它失败并出现错误.

Class class = home.Student.class;
Field field = studentClass.getDeclaredField("nstance");
Object obj = field.get(null);
Run Code Online (Sandbox Code Playgroud)

我得到的例外是:

java.lang.IllegalAccessException: Class com.test.ReflectionTest can not access a member of class home.Student with modifiers "private static".
Run Code Online (Sandbox Code Playgroud)

此外,我需要使用以下代码调用私有.

Method method = studentClass.getMethod("addMarks");
method.invoke(studentClass.newInstance(), 1);
Run Code Online (Sandbox Code Playgroud)

但问题是Student类是单例类,而构造函数是私有的,无法访问.

Kai*_*Kai 82

您可以设置可访问的字段:

field.setAccessible(true);
Run Code Online (Sandbox Code Playgroud)


Ale*_*aho 13

是的.你必须设置它们访问使用setAccessible(true)定义AccesibleObject这是一个超类的都FieldMethod

使用静态字段,您应该能够:

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
Run Code Online (Sandbox Code Playgroud)

并使用私有方法

Method method = studentClass.getMethod("addMarks");
method.setAccessible(true); // exactly the same as with the field
method.invoke(studentClass.newInstance(), 1);
Run Code Online (Sandbox Code Playgroud)

并使用私有构造函数:

Constructor constructor = studentClass.getDeclaredConstructor(param, types);
constructor.setAccessible(true);
constructor.newInstance(param, values);
Run Code Online (Sandbox Code Playgroud)