首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Java反射检索继承的属性名称/值

使用Java反射检索继承的属性名称/值
EN

Stack Overflow用户
提问于 2009-06-25 09:11:22
回答 12查看 89.6K关注 0票数 151

我有一个Java对象'ChildObj‘,它是从'ParentObj’扩展而来的。现在,是否可以使用Java反射机制检索ChildObj的所有属性名称和值,包括继承的属性?

Class.getFields提供了公共属性的数组,Class.getDeclaredFields提供了所有字段的数组,但是它们都没有包含继承的字段列表。

有没有办法也检索继承的属性?

EN

回答 12

Stack Overflow用户

回答已采纳

发布于 2009-06-25 09:17:28

不,你需要自己写。这是一个在Class.getSuperClass()上调用的简单递归方法

代码语言:javascript
复制
public static List<Field> getAllFields(List<Field> fields, Class<?> type) {
    fields.addAll(Arrays.asList(type.getDeclaredFields()));

    if (type.getSuperclass() != null) {
        getAllFields(fields, type.getSuperclass());
    }

    return fields;
}

@Test
public void getLinkedListFields() {
    System.out.println(getAllFields(new LinkedList<Field>(), LinkedList.class));
}
票数 205
EN

Stack Overflow用户

发布于 2010-03-09 08:15:57

代码语言:javascript
复制
    public static List<Field> getAllFields(Class<?> type) {
        List<Field> fields = new ArrayList<Field>();
        for (Class<?> c = type; c != null; c = c.getSuperclass()) {
            fields.addAll(Arrays.asList(c.getDeclaredFields()));
        }
        return fields;
    }
票数 97
EN

Stack Overflow用户

发布于 2014-05-28 23:27:21

如果您想要依赖于库来完成此任务,Apache Commons Lang version 3.2+提供了FieldUtils.getAllFieldsList

代码语言:javascript
复制
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));
    }
}
票数 39
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1042798

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档