Getting first parent's fields via reflection

2020-02-26 08:59发布

问题:

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)?

回答1:

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.



回答2:

Create a method

public static void printFieldsFor(Class cls, Object obj) {
  Field[] fields = cls.getDeclaredFields();
  for ( Field field : fields ) {
    String fieldName = field.getName();
    String fieldValue = field.get(obj);
  }
}

printFieldsFor(object.getClass(), obj);
printFieldsFor(object.getClass().getSuperclass(), obj);

or use a loop

for(Class cls = object.getClass(); 
    cls!=null && cls!=A.class; 
    cls = cls.getSuperclass()) {
  for(Field field : cls.getDeclaredFields()) {
     String fieldName = field.getName();
     String fieldValue = field.get(obj);
     // do something with the field.
  }
}


回答3:

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author pablo.barbosa (2017-08-15)
 */
public class ReflectionUtil {

    /**
     * Hiding constructor. The methods are statics
     */
    private ReflectionUtil() {
        // Hiding constructor
    }

    public static List<Field> getInheritedDeclaredFields(Class<?> fromClass, Class<?> stopWhenClass) {
        if (stopWhenClass == null) {
            stopWhenClass = Object.class;
        }
        List<Field> fields = new ArrayList<>();
        List<Class<?>> classes = new ArrayList<>();

        Class<?> cls = fromClass;
        do {
            classes.add(cls);
            cls = cls.getSuperclass();
        } while (cls != null && !cls.equals(stopWhenClass));

        for (int i = classes.size() - 1; i >= 0; i--) {
            fields.addAll(Arrays.asList(classes.get(i).getDeclaredFields()));
        }

        return fields;
    }

    public static Field getInheritedDeclaredField(Class<?> fromClass, String fieldName, Class<?> stopWhenClass) throws NoSuchFieldException {
        if (stopWhenClass == null) {
            stopWhenClass = Object.class;
        }

        Class<?> cls = fromClass;
        do {
            Field field;
            try {
                field = cls.getDeclaredField(fieldName);
                if (field != null) {
                    return field;
                }
            } catch (NoSuchFieldException | SecurityException e) {
                // Nothing. We'll try to get field from superclass
            }
            cls = cls.getSuperclass();
        } while (cls != null && !cls.equals(stopWhenClass));

        // If we got here, we'll throw an exception
        throw new NoSuchFieldException(fieldName);
    }

    public static Object getInheritedDeclaredFieldValue(Object obj, String fieldName, Class<?> stopWhenClass) throws NoSuchFieldException, IllegalAccessException {
        Field field = getInheritedDeclaredField(obj.getClass(), fieldName, stopWhenClass);
        field.setAccessible(true);
        return field.get(obj);
    }

}


回答4:

you can simply get fields from any class using this code no mater its parent or child class

for (Field field : YourClassName.class.getDeclaredFields()) {
  //fields
}