Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Reflection - Get Fields From Sub Class as well as Super Class

Tags:

java

I am using inherited bean classes for my project. Here some of super classes will be empty and sub class can have fields & some of sub classes will be empty and super class can have fields.

My requirement is to get all private / public fields from Sub class as well as to get all public / protected fields from Super class too.

Below I have tried to achieve it. But I failed to meet my requirement. Please provide some suggestion to achieve this one.

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

If I use above code, I can get only Super class fields

Field fields [] = obj.getClass().getFields();

If I use above code, I can get all fields from Sub class and super class fields

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

If I use above code, I can get Sub class public and private all fields.

like image 567
deadend Avatar asked Dec 23 '16 07:12

deadend


People also ask

What happens if both super class and sub class have a field with same name?

When a subclass defines a field with the same name, the subclass just declares a new field. The field in the superclass is hidden. It is NOT overridden, so it can not be accessed polymorphically.

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.

Can superclass access subclass fields Java?

No, a superclass has no knowledge of its subclasses.

How do I get fields from parent class?

Now how can i get fields of parent class in this case 'a'. You can use getField() with public fields. Otherwise, you need to loop through parent classes yourself.


1 Answers

You will have to iterate over all the superclasses of your class, like this:

private List<Field> getInheritedPrivateFields(Class<?> type) {
    List<Field> result = new ArrayList<Field>();

    Class<?> i = type;
    while (i != null && i != Object.class) {
        Collections.addAll(result, i.getDeclaredFields());
        i = i.getSuperclass();
    }

    return result;
}
like image 173
jqno Avatar answered Sep 27 '22 00:09

jqno