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 access the private methods of a class using java reflection package.
Using reflection in C# language, we can access the private fields, data and functions etc.
Despite the common belief it is actually possible to access private fields and methods of other classes via Java Reflection. It is not even that difficult. This can be very handy during unit testing.
We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java). We can do this by changing the runtime behavior of the class by using some predefined methods of Java.
You can set the field accessible:
field.setAccessible(true);
Yes it is. You have to set them accessible using setAccessible(true)
defined in AccesibleObject that is a super class of both Field
and Method
With the static field you should be able to do:
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
And with the private method
Method method = studentClass.getMethod("addMarks"); method.setAccessible(true); // exactly the same as with the field method.invoke(studentClass.newInstance(), 1);
And with a private constructor:
Constructor constructor = studentClass.getDeclaredConstructor(param, types); constructor.setAccessible(true); constructor.newInstance(param, values);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With