I was trying to fetch the value of an static private attribute via reflection, but it fails with an error.
Class class = home.Student.class;
Field field = studentClass.getDeclaredField("nstance");
Object obj = field.get(null);
The exception I get is:
java.lang.IllegalAccessException: Class com.test.ReflectionTest can not access a member of class home.Student with modifiers "private static".
Moreover, there is a private I need to invoke, with the following code.
Method method = studentClass.getMethod("addMarks");
method.invoke(studentClass.newInstance(), 1);
but the problem is the Student class is a singleton class, and constructor in private, and cannot be accessed.
解决方案
You can set the field accessible:
field.setAccessible(true);