Alex Rivera | Logout

Getting first parent's fields via reflection

Asked 2011-11-01T12:30:23.890
18

I'm trying to get the fields and values of my object's first parent. My current code is this:

Class<? extends Object> cls = obj.getClass();
Field[] fields = cls.getDeclaredFields();
for ( Field field : fields )
{
    String fieldName = field.getName();
    String fieldValue = field.get(obj);
}

My class structure is similar to this:

class A
{
    int x;
}

class B extends A
{
    int y;
}

class C extends B
{
    int z;
}

Now, I pass a C object to the method and I want to get all fields from C and B, but not from A. Is there a way to do this (using reflection, I don't want to implement other methods)?

Edit
Report

1 Answer

28

Luchian, use the getSuperclass() method to obtain a reference to a Class object that represents a superclass type of the object in question. After that it is going to be easy for you to get fields the same way you do in your example.

answered 2011-11-01T12:37:31.907

Your Answer