How can I access an inherited protected field from an object by 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.
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.
You can access the private methods of a class using java reflection package.
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); } }
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