使用 Java 反射检索继承的属性名称/值 [英] Retrieving the inherited attribute names/values using Java Reflection

查看:32
本文介绍了使用 Java 反射检索继承的属性名称/值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've a Java object 'ChildObj' which is extended from 'ParentObj'. Now, if it is possible to retrieve all the attribute names and values of ChildObj, including the inherited attributes too, using Java reflection mechanism?

Class.getFields 给我公共属性数组,Class.getDeclaredFields 给了我所有字段的数组,但没有一个包含继承的字段列表.

Class.getFields gives me the array of public attributes, and Class.getDeclaredFields gives me the array of all fields, but none of them includes the inherited fields list.

有什么办法也可以检索继承的属性吗?

Is there any way to retrieve the inherited attributes also?

推荐答案

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

no, you need to write it yourself. It is a simple recursive method called on Class.getSuperClass():

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

这篇关于使用 Java 反射检索继承的属性名称/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆