Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java reflection - access protected field

How can I access an inherited protected field from an object by reflection?

like image 509
Moro Avatar asked Apr 09 '09 17:04

Moro


People also ask

How do you inherit fields using reflection?

The only way we have to get only inherited fields is to use the getDeclaredFields() method, as we just did, and filter its results using the Field::getModifiers method. This one returns an int representing the modifiers of the current field. Each possible modifier is assigned a power of two between 2^0 and 2^7.

How do you set up a private field in a reflection?

If we want to access Private Field and method using Reflection we just need to call setAccessible(true) on the field or method object which you want to access. Class. getDeclaredField(String fieldName) or Class. getDeclaredFields() can be used to get private fields.

Can reflection access private methods?

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


1 Answers

Two issues you may be having issues with - the field might not be accessible normally (private), and it's not in the class you are looking at, but somewhere up the hierarchy.

Something like this would work even with those issues:

public class SomeExample {    public static void main(String[] args) throws Exception{     Object myObj = new SomeDerivedClass(1234);     Class myClass = myObj.getClass();     Field myField = getField(myClass, "value");     myField.setAccessible(true); //required if field is not normally accessible     System.out.println("value: " + myField.get(myObj));   }    private static Field getField(Class clazz, String fieldName)         throws NoSuchFieldException {     try {       return clazz.getDeclaredField(fieldName);     } catch (NoSuchFieldException e) {       Class superClass = clazz.getSuperclass();       if (superClass == null) {         throw e;       } else {         return getField(superClass, fieldName);       }     }   } }  class SomeBaseClass {   private Integer value;    SomeBaseClass(Integer value) {     this.value = value;   } }  class SomeDerivedClass extends SomeBaseClass {   SomeDerivedClass(Integer value) {     super(value);   } } 
like image 192
kenj0418 Avatar answered Sep 19 '22 05:09

kenj0418