Java reflection: Find fields of a subclass

java reflection get all fields recursively
java reflection get field value
java reflection get subclasses
java reflection get nested field
java reflection use case
java reflection interface
java 8 reflection
java reflection create instance

I have a class hierarchy like so: (=> means "is a subclass of")

anonymous instance class => abstract class => generic abstract class

or more succinctly:

C => B => A

When executing, "C" calls one of "A"'s methods. Within that method in "A", I want to use reflection to find protected fields of the object that are defined in class "B". (So these are fields that "C" and "B" can see, but not "A".)

How would I do this with Java reflection? And how can I future-proof it in case I add something between A & B or B & C?

You have to use getDeclaredFields() repeatedly on each class in the inheritance hierarchy of your object's class (via getSuperclass()).

However, what you are planning sounds like a nasty violation of the concept of inheritance. The best way of future-proofing would be to avoid this kind of thing entirely. What are you trying to do that you think requires such reflection shenanigans?

Retrieve Fields from a Java Class Using Reflection, Learn how to get the fields of a class using reflection, including inherited fields. In Java, we achieve this by using the Java Reflection API. Let's assume we have a subclass of Employee or a superclass of Person – then� FULL PRODUCT VERSION : java version "1.5.0_04" Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_04-b05) Java HotSpot(TM) Client VM (build 1.5.0_04-b05, mixed mode, sharing) 1.5.0_06-b05 1.6.0-rc-b68 A DESCRIPTION OF THE PROBLEM : A subclass can't access its superclass's protected fields and methods by reflection.

As far as I know, there is no way to know about your "child classes" in Java reflectively. Wouldn't a better solution be to create an abstract method on A that B would have to implement, and call that instead?

public class A {
   //other stuff here
   protected void abstract mySubMethod();
   //other stuff here
}

Edit: If I have misunderstood your question, and you actually want to know about parent classes, then yes: getDeclaredFields() is the correct reflective method to use, as mentioned by other posters.

Additional Edit: I hate to keep modifying this answer, but... In general, if you are attempting to give access to a parent class, the "correct" and "future proof" way to do this is to create abstract methods that are getters or setters (or even more complex, if necessary) and then have the children honor those or not, and respond as appropriate.

That being said, you can do something like the others have said:

getClass().getParentClass().getDeclaredFields()

However, that would only work if C is always directly inherited from B. Reflections is, by it's very nature, tricky and specific. I have to do a LOT of it on a project I am on (don't ask, trust me, you DON'T want to know), and I avoid it whenever possible. Unless there is a good reason for A to need the protected fields and it is discovering information about them, then you would likely want to use an abstract method. I would also submit that it is likely that you can solve the other problem with an abstract method, however it might be a little bit harder.

Guide to Java Reflection, To get access to the class, method, and field information of an We will now use Java reflection to discover the names of all fields of this class. that interface, but the subclass does not directly declare that interface with the� Java Reflection provides a lot of information about a given class at runtime; you can easily know all its super classes, implemented interfaces, methods, constructors, fields, and so on. But in some cases, you may want to know all the classes implementing a given interface, or subclassing a given class. This tip, based on lessons learned from Java Tip 105, shows you how to retrieve all the

Field[] fields = getClass().getSuperclass().getDeclaredFields();

And then iterate those fields and get the ones you want.

In case your hierarchy grows, you can transform the above to a recursive calls to getSuperclass() (while getSuperclass() != Object.class), thus collecting all fields of all superclasses.

Reflection in Java, All Java classes are subclasses of a pre-defined base class called Object: about super classes, we can also find out about the methods and fields of a class. Java Reflection provides ability to inspect and modify the runtime behavior of application. Reflection in Java is one of the advance topic of core java. Using java reflection we can inspect a class, interface, enum, get their structure, methods and fields information at runtime even though class is not accessible at compile time.

Example of recursive method for java 8+

static final Field[] getDeclaredFields(Class clazz) {
    final Field[] fields = clazz.getDeclaredFields();

    if ( clazz.getSuperclass() != Object.class ) {
        final Field[] pFields = getDeclaredFields(clazz.getSuperclass());
        final Field[] allFields = new Field[fields.length + pFields.length];
        Arrays.setAll(allFields, i -> (i < pFields.length ? pFields[i] : fields[i - pFields.length]));
        return allFields;
    } else
        return fields;
}

Inherited equals() in subclass with added fields, ID: java/inherited-equals-with-added-fields. Kind: problem. Severity: warning To get the correct result, you must override Square.equals in class Rectangle . Java: Accessing private fields of superclass through reflection You use Class.getSuperclass , Class.getDeclaredField and AccessibleObject.setAccessible as follows:

Java Reflection Example Tutorial, Reflection Class, Methods, Fields, Constructors, Annotations. Using java reflection we can inspect a class, interface, enum, get their structure, helps frameworks in making sure that the Class retrieved is subclass of framework Base Class. Welcome to the Ranch The Oracle/Sun API documentation has a “known subclasses” link, but that will probably not find all the subclasses. It is not a usual requirement of object-orientation that a superclass “know” anything about its subclasses.

Java Tip 113: Identify subclasses at runtime, Java Reflection provides a lot of information about a given class at runtime; you all its super classes, implemented interfaces, methods, constructors, fields, and so on. You can refine the find() method to find any subclass of a given class. IllegalAccessException: if this Field object is enforcing Java language access control and the underlying field is either inaccessible or final.; IllegalArgumentException: if the specified object is not an instance of the class or interface declaring the underlying field (or a subclass or implementor thereof), or if an unwrapping conversion fails.

Obtaining Field Types (The Java™ Tutorials > The Reflection API , There are eight primitive types: boolean , byte , short , int , long , char , float , and double . A reference type is anything that is a direct or indirect subclass of java. Basically, my requirement is to get the superclass object by using reflection so that i can get the field name and its value. so, I have a class as

Comments
  • Just so I am sure I understand - You want to call a method on a Subclass of A, right? i.e. B inherits from A, and you want A to call a method on B?
  • well, specifically I want to dynamically access fields defined on B from a method defined in A. But the declared type of the class is C.
  • I don't understand what you want to future-proof, should the reflection always reference the same class as B?, is B known at compile time? How do you discern which class in your inheritance chain is B if it isn't its position?
  • @josefx That was my confusion as well. That is why I suggested an abstract method, if A always needs access to this data but doesn't know what it is, and you could use a NullObject for implementations that don't care about the data.
  • First I was pissed off. Then I tried to explain what my purpose was, but couldn't without discussing the whole problem. Then I got more pissed off. Then as I was laying my son to sleep, I saw that my problem could be solved much more cleanly without reflection by having the super class create the child objects and store them locally. Thanks for the kick in the pants.
  • OK, just to make sure I am not crazy - did I completely misread his question? Or is he in fact asking how a parent class would find a method on a child class? Because your method would work if he was asking about methods on the parent class, but I am reading that he is asking the opposite.
  • @aperkins,this should work with methods of the child class too, because the getClass() will return the actual class of the Object at runtime (A) the getSuperclass() will then return the class (B), but it is not future-proof.
  • Yeah, I realized that after I thought about it. It is too early in the morning, and the winter crud is killing my brain. At least, that is my excuse, and I am sticking to it. :) I updated my answer appropriately. Thanks for the response.