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

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

问题描述

我有一个Java对象'ChildObj',它是从'ParentObj'扩展而来的。现在,如果可以使用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 Reflection检索继承的属性名称/值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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