java 通过反射获取第一个父级的字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7966466/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:14:50  来源:igfitidea点击:

Getting first parent's fields via reflection

javareflection

提问by Luchian Grigore

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

现在,我将一个 C 对象传递给该方法,我想从 C 和 B 中获取所有字段,而不是从 A 中获取。有没有办法做到这一点(使用反射,我不想实现其他方法)?

回答by DejanLekic

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.

Luchian,使用getSuperclass()方法获取对 Class 对象的引用,该对象表示所讨论对象的超类类型。之后,您将很容易以与示例中相同的方式获取字段。

回答by Peter Lawrey

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.
  }
}

回答by Pablo de Castro Barbosa

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);
    }

}

回答by Muhammad Suleman

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
}