我试图通过反射获取静态私有属性的值,但它失败并出现错误.
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类是单例类,而构造函数是私有的,无法访问.
Ale*_*aho 13
是的.你必须设置它们访问使用setAccessible(true)定义AccesibleObject这是一个超类的都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
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)
| 归档时间: |
|
| 查看次数: |
29063 次 |
| 最近记录: |