views:

1579

answers:

5

I've a Java object 'ChildObj' which is extended from 'ParentObj'. Now, if it is possible to retrieve all the attribute names and values of ChildObj, including the inherited attributes too, using Java reflection mechanism?

Class.getFields gives me the array of public attributes, and Class.getDeclaredFields gives me the array of all fields, but none of them includes the inherited fields list.

Is there any way to retrieve the inherited attributes also?

+7  A: 

no, you need to write it yourself. It is a simple recursive method called on Class.getSuperClass():

public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
    for (Field field: type.getDeclaredFields()) {
        fields.add(field);
    }

    if (type.getSuperclass() != null) {
        fields = getAllFields(fields, type.getSuperclass());
    }

    return fields;
}

@Test
public void getLinkedListFields() {
    System.out.println(getAllFields(new LinkedList<Field>(), LinkedList.class));
}
dfa
yes. thought about that. but wanted to check if there is any other way to do that. thanks. :)
Veera
it worked. thanks.
Veera
Passing an mutable argument in and returning it probably isn't a great design. fields.addAll(type.getDeclaredFields()); would be more conventional than a enhanced for loop with add.
Tom Hawtin - tackline
feel free to change edit my code :-)
dfa
I'd feel the need to at least compile it (on stackoverflow!), and probably add in a little Arrays.asList.
Tom Hawtin - tackline
+2  A: 

You need to call:

Class.getSuperClass().getDeclaredFields()

Recursing up the inheritance hierarchy as necessary.

Nick Holt
+1  A: 

You can try:

   Class parentClass = getClass().getSuperclass();
   if (parentClass != null) {
      parentClass.getDeclaredFields();
   }
Manuel Selva
A: 
 private static void addDeclaredAndInheritedFields(Class c, Collection<Field> fields) {

fields.addAll(Arrays.asList(c.getDeclaredFields())); Class superClass = c.getSuperclass(); if (c != null) { addDeclaredAndInheritedFields(superClass, fields); } }

DidYouMeanThatTomHawtin
+3  A: 
    public static List<Field> getInheritedFields(Class<?> type) {
        List<Field> fields = new ArrayList<Field>();
        for (Class<?> c = type; c != null; c = c.getSuperclass()) {
            fields.addAll(Arrays.asList(c.getDeclaredFields()));
        }
        return fields;
    }
Esko Luontola