Tuesday, August 5, 2014

Recursively get all fields for a hierarchical class tree

Hi friends, it took quite a long time to again post something worthy. Normally when we play with reflection, we get metadata only about the targeted class, not anything inherited. This will try to resolve that part. We will get targeted class & it's inherited fields as well.

Any feedback is always welcome. Please do not hesitate in case you have any.


public class testReflection {
    public static void main(String[] args) {
        try {
            C c = new C();
            Class klass = c.getClass();
            Field[] fields = getAllFields(klass);
            for (Field field : fields) {
                System.out.println(field.getName());
            }
        catch (Throwable a_th) {
            a_th.printStackTrace();
        }
    }

    public static Field[] getAllFields(Class klass) {
        List fields = new ArrayList();
        fields.addAll(Arrays.asList(klass.getDeclaredFields()));
        if (klass.getSuperclass() != null) {
            fields.addAll(Arrays.asList(getAllFields(klass.getSuperclass())));
        }
        return fields.toArray(new Field[] {});
    }
}

class {
    public String    nameA    = "";
}

class extends {
    public String    nameB    = "";
    public String    nameB1    = "";
    public String    nameB2    = "";
}

class extends {
    public String    nameC    = "";
}