从类中获取所有字段(甚至私有和继承) [英] Get all fields (even private and inherited) from class

查看:882
本文介绍了从类中获取所有字段(甚至私有和继承)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在进行大学项目。

我需要从课堂上获取所有字段。甚至私人和继承。我试图获取所有声明的字段,然后转换为超类并重复。
我的代码片段:

I am making university project.
I need to get all fields from class. Even private and inherited. I tried to get all declared fields and then cast to super class and repeat. Fragment of my code:

private void listAllFields(Object obj) {
    List<Field> fieldList = new ArrayList<Field>();
    while (obj != null) {
        fieldList.addAll(Arrays.asList(obj.getClass().getDeclaredFields()));
        obj = obj.getClass().getSuperclass().cast(obj);
    }
    // rest of code

但它不起作用。 tmpObj 投射后仍然是同一个类(不是超类)。

我将非常感谢如何修复投射问题,或者如何检索这些字段以不同的方式。

But it does not work. tmpObj after casting is still the same class (not superclass).
I will appreciate any help how to fix casting problem, or how to retrieve these fields in different way.

编辑:

问题不是获取字段的访问权限,而是获取字段名称!

我这样管理:

Problem is not to gain access to fields, but to get names of fields!
I manages it that way:

private void listAllFields(Object obj) {
    List<Field> fieldList = new ArrayList<Field>();
    Class tmpClass = obj.getClass();
    while (tmpClass != null) {
        fieldList.addAll(Arrays.asList(tmpClass .getDeclaredFields()));
        tmpClass = tmpClass .getSuperclass();
    }
    // rest of code


推荐答案

obj = obj.getClass().getSuperclass().cast(obj);

此行不符合您的预期。转换对象实际上并没有改变它,它只是告诉编译器将其视为其他东西。

This line does not do what you expect it to do. Casting an Object does not actually change it, it just tells the compiler to treat it as something else.

例如。您可以将列表投射到集合,但它仍然是List。

E.g. you can cast a List to a Collection, but it will still remain a List.

但是,通过超类循环访问字段可以正常工作而不需要转换:

However, looping up through the super classes to access fields works fine without casting:

Class<?> current = yourClass;
while(current.getSuperclass()!=null){ // we don't want to process Object.class
    // do something with current's fields
    current = current.getSuperclass();
}

BTW,如果你有权访问Spring Framework,有一个方便的方法循环遍历类和所有超类的字段:

ReflectionUtils.doWithFields(baseClass,FieldCallback)

(另见我之前的答案:访问私有继承字段通过Java中的反射

BTW, if you have access to the Spring Framework, there is a handy method for looping through the fields of a class and all super classes:
ReflectionUtils.doWithFields(baseClass, FieldCallback)
(also see this previous answer of mine: Access to private inherited fields via reflection in Java)

这篇关于从类中获取所有字段(甚至私有和继承)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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