6

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.

deadend
  • 1,286
  • 6
  • 31
  • 52
  • What if you iterate through the subclass->superclass chain and collect the fields? – Lyubomyr Shaydariv Dec 23 '16 at 07:35
  • 2
    It looks like you already know how to get all the data you want, so what's the problem? If you think you should be able to get it all in one call, that's probably the mistake. You might have to make multiple calls, and you might have to filter out some of the data. But I don't understand what you're trying to accomplish and why some combination of your examples doesn't accomplish that. – ajb Dec 23 '16 at 07:36
  • @ ajb. i am attempting to get in one call for both sub and super class fields. Noted your point and Thanks for your reply. – deadend Dec 23 '16 at 07:42
  • @ Lyubomyr Shaydariv.. Yes in am using Sub class object to get all fields in sub and super classes. – deadend Dec 23 '16 at 07:43
  • Possible duplicate of [Retrieving the inherited attribute names/values using Java Reflection](https://stackoverflow.com/questions/1042798/retrieving-the-inherited-attribute-names-values-using-java-reflection) – Vadzim May 28 '19 at 13:03

1 Answers1

7

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;
}
jqno
  • 15,133
  • 7
  • 57
  • 84