Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to invoke private attributes or methods via reflection

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.

like image 876
M.J. Avatar asked Aug 02 '11 11:08

M.J.


People also ask

Can we access private methods using reflection?

You can access the private methods of a class using java reflection package.

Can we access private methods using reflection C#?

Using reflection in C# language, we can access the private fields, data and functions etc.

Can Java reflection API access private fields and methods of a class?

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.

Can a private method can be called from outside the class it is defined in?

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.


2 Answers

You can set the field accessible:

field.setAccessible(true); 
like image 192
Kai Avatar answered Oct 13 '22 20:10

Kai


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); 
like image 31
Aleksi Yrttiaho Avatar answered Oct 13 '22 21:10

Aleksi Yrttiaho