通过反射获取第一个父母的字段 [英] Getting first parent's fields via reflection

查看:45
本文介绍了通过反射获取第一个父母的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取对象的第一个父项的字段和值.我当前的代码是这样:

I'm trying to get the fields and values of my object's first parent. My current code is this:

Class<? extends Object> cls = obj.getClass();
Field[] fields = cls.getDeclaredFields();
for ( Field field : fields )
{
    String fieldName = field.getName();
    String fieldValue = field.get(obj);
}

我的班级结构与此类似:

My class structure is similar to this:

class A
{
    int x;
}

class B extends A
{
    int y;
}

class C extends B
{
    int z;
}

现在,我将C对象传递给该方法,并且我想从C和B中获取所有字段,而不是从A中获取所有字段.有没有一种方法可以做到这一点(使用反射,我不想实现其他方法)?

Now, I pass a C object to the method and I want to get all fields from C and B, but not from A. Is there a way to do this (using reflection, I don't want to implement other methods)?

推荐答案

卢西安(Luchian),请使用

Luchian, use the getSuperclass() method to obtain a reference to a Class object that represents a superclass type of the object in question. After that it is going to be easy for you to get fields the same way you do in your example.

这篇关于通过反射获取第一个父母的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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