0

I was trying to find a private field using reflection with a given name, which may also reside in parent class or somewhere else in the inheritance hierarchy.

But I found out that there is no such method in Class which provides this information.

Class#getDeclaredFields() - provides all fields private, public but does not include inheritance hierarchy

Class#getFields() - includes inheritance hierarchy but searches only public fields.

So why is there no method that provides both types of information?

I know this can easily be implemented and there are libraries that provide this, but still can be included in java itself.

Narendra Pathai
  • 41,187
  • 18
  • 82
  • 120

1 Answers1

0

This is because a child class is not aware of any private fields in a parent class - it does not inherit them.

The problem at hand can be solved very easily by walking up the class hierarchy with getSuperClass

public static Field getField(final Class<?> toReflectOn, final String fieldName) throws NoSuchFieldException {
    try {
        return toReflectOn.getField(fieldName);
    } catch (NoSuchFieldException ex) {
        if (toReflectOn.getSuperclass() != null) {
            return getField(toReflectOn.getSuperclass(), fieldName);
        }
        throw ex;
    }
} 

This other SO post provides a more sophisticated approach that loops over all fields in the class hierarchy.

Community
  • 1
  • 1
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166