Is it possible to invoke private attributes or methods via reflection

JavaReflection

Java Problem Overview


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.

Java Solutions


Solution 1 - Java

You can set the field accessible:

field.setAccessible(true);

Solution 2 - Java

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);

Solution 3 - Java

Yes, you can "cheat" like this:

    Field somePrivateField = SomeClass.class.getDeclaredField("somePrivateFieldName");
    somePrivateField.setAccessible(true); // Subvert the declared "private" visibility
    Object fieldValue = somePrivateField.get(someInstance);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionM.J.View Question on Stackoverflow
Solution 1 - JavaKaiView Answer on Stackoverflow
Solution 2 - JavaAleksi YrttiahoView Answer on Stackoverflow
Solution 3 - JavaBohemianView Answer on Stackoverflow