简体   繁体   中英

Access protected fields of a subclass in a superclass?

Is it possible to access a protected member from Subclass in a SuperClass using reflection?

private void accessFields() {
    Field[] fields = this.getClass().getDeclaredFields();
    for(Field field : fields) {
        if(Modifier.isProtected(field.getModifiers()) {
            //Will this always work? Or will get(this) throw an IllegalAccessException?
            Object value = field.get(this);
        }
    }
}

Note that this would be the opposite way of the common protected member access, not the SubClass accesses the protected member, but the SuperClass .

You can do anything with reflection. You can even directly manipulate the memory of the JVM if you feel like it ( sun.misc.Unsafe ).

However, if you don't normally have access, you'll need to use setAccessible or similar.

You can access any field of an object (private, protected, public) using reflection. It doesn't matter if the class accessing the private fields of an object is its super class or sub class (when using reflection).

PrivateObject privateObject = new PrivateObject("The Private Value");

Field privateStringField = PrivateObject.class.
        getDeclaredField("privateString");

privateStringField.setAccessible(true);

String fieldValue = (String) privateStringField.get(privateObject);
System.out.println("fieldValue = " + fieldValue);

As long as you can get an object of the PrivateObject Class, you can access its fields. Do remember to field.setAccessible(true) to access non-public fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM