Bel
Bel

Reputation: 312

Getting sub class fields via reflection

I got 2 classes: B extends A.

I use getDeclaratedFields() on class B, and I don't get fields from class `A.

How can I get them?

Upvotes: 1

Views: 210

Answers (2)

A4L
A4L

Reputation: 17595

You should use Class#getSuperclass() to access the super class of a classand get its fields too using Class#getDeclaredFields(), repeat (recursively) until you reach Object or a class of your choice where you want to stop.

Here is some sample code:

@Test
public void getDeclFieldsIncludingBase() {
    List<Field> fields = new ArrayList<>();
    getDeclFieldsIncludingBase(B.class, fields);
    for(Field f : fields) {
        System.out.println(f.getName());    
    }
}

private void getDeclFieldsIncludingBase(Class<?> cl, List<Field> fields) {
    Field[] declaredFields = cl.getDeclaredFields();
    for(Field f : declaredFields) {
        fields.add(f);
    }
    Class<?> superclass = cl.getSuperclass();
    if(! Object.class.equals(superclass)) {
        getDeclFieldsIncludingBase(superclass, fields);
    }
}

Example:

public class A {
    int a;
}

and

public class B extends A {
    int b;
}

The output should be

b
a

Upvotes: 0

Sachin Gorade
Sachin Gorade

Reputation: 1467

getDeclaredFields() returns fields which are declared by the class and not the super class.

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.

Use getFields method to retrieve fields declared by class and super class.

Specifically, if this Class object represents a class, this method returns the public fields of this class and of all its superclasses

Read Java Class for more information.

Upvotes: 1

Related Questions