获取类层次结构的所有字段

Dmi*_*pov 2 java reflection class

我有课:

ClassA{
 public String filedA;
}

ClassB extends ClassA{
 public String filedB;
}

ClassC extends ClassB{
 public String filedC;
}
Run Code Online (Sandbox Code Playgroud)

然后我创建对象:

ClassC c=new ClassC();
c.fieldC="TestC";
c.fieldA="TestA";
c.fieldB="TestB";
Run Code Online (Sandbox Code Playgroud)

在我尝试获取所有字段后,我打电话

Field[] fields=c.getClass().getDeclaredFields();
Run Code Online (Sandbox Code Playgroud)

但我只有一个项目的阵列

fields[fieldC]
Run Code Online (Sandbox Code Playgroud)

如何从所有类中获取所有字段包括扩展?

tjg*_*184 10

请尝试以下方法:

Field[] fields = c.getClass().getFields();
Run Code Online (Sandbox Code Playgroud)

如果需要所有超类字段,请参阅以下内容:

使用Java Reflection检索继承的属性名称/值


log*_*off 6

您的C类不会扩展任何类.然后,getDeclaredFields()只返回String filedC你所看到的.你做不到c.fieldA="TestA",c.fieldB="TestB"因为你的班级没有声明这个字段.无论如何,在C扩展B和B扩展A的情况下,方法getFields()仅返回公共字段(包括继承):

返回一个包含Field对象的数组,该对象反映此Class对象所表示的类或接口的所有可访问公共字段.

getDeclaredFields()返回在类中声明(不含继承)的所有字段:

返回Field对象的数组,这些对象反映由此Class对象表示的类或接口声明的所有字段.这包括公共,受保护,默认(包)访问和私有字段,但不包括继承的字段.


mad*_*adx 6

如果您不想重新发明轮子,您可以依赖Apache Commons Lang 3.2+ 版,它提供FieldUtils.getAllFieldsList

import java.lang.reflect.Field;
import java.util.AbstractCollection;
import java.util.AbstractList;
import java.util.AbstractSequentialList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.reflect.FieldUtils;
import org.junit.Assert;
import org.junit.Test;

public class FieldUtilsTest {

    @Test
    public void testGetAllFieldsList() {

        // Get all fields in this class and all of its parents
        final List<Field> allFields = FieldUtils.getAllFieldsList(LinkedList.class);

        // Get the fields form each individual class in the type's hierarchy
        final List<Field> allFieldsClass = Arrays.asList(LinkedList.class.getFields());
        final List<Field> allFieldsParent = Arrays.asList(AbstractSequentialList.class.getFields());
        final List<Field> allFieldsParentsParent = Arrays.asList(AbstractList.class.getFields());
        final List<Field> allFieldsParentsParentsParent = Arrays.asList(AbstractCollection.class.getFields());

        // Test that `getAllFieldsList` did truly get all of the fields of the the class and all its parents 
        Assert.assertTrue(allFields.containsAll(allFieldsClass));
        Assert.assertTrue(allFields.containsAll(allFieldsParent));
        Assert.assertTrue(allFields.containsAll(allFieldsParentsParent));
        Assert.assertTrue(allFields.containsAll(allFieldsParentsParentsParent));
    }
}
Run Code Online (Sandbox Code Playgroud)