简体   繁体   English

使用反射访问Java中子类和超类的属性

[英]Accessing properties of subclasses and superclasses in java with reflection

I have a number of classes that derive from the same base type. 我有许多派生自相同基本类型的类。 The base type contains all the members common to the subclasses. 基本类型包含子类共有的所有成员。 When subclass is instantiated, I need to access its members through reflection. 当实例化子类时,我需要通过反射来访问其成员。 I need to access all the members of each subclass, but I need to isolate those members that exist in the base class from those that exists in subclasses. 我需要访问每个子类的所有成员,但是我需要将基类中存在的那些成员与子类中存在的那些成员隔离。 For instance: 例如:

public abstract class mainBaseClass{
    public String firstname;
    public String lastname;
}
public class subClass extends mainBaseClass{
    public String property1;
    public String property2;
}

I am accessing members as follows: 我正在按以下方式访问成员:

Field[] fields = objectName.getClass().getFields();
for(Field f : fields){
    Log.d("FIELD NAME", f.getName());
}

When I use reflection to expose the properties contained in an instance of "subClass" how would I differentiate 'firstname' and 'lastname' from 'property1' and 'property2'? 当我使用反射来暴露“ subClass”实例中包含的属性时,如何区分“ firstname”和“ lastname”与“ property1”和“ property2”?

I'm not sure how to implement this. 我不确定如何实现这一点。 Can somebody offer a solution or maybe a place to look? 有人可以提供解决方案还是一个寻找地方的地方? Thank you! 谢谢! Vivian 维维安

Use Class#getDeclaredFields() instead. 请改用Class#getDeclaredFields() Java-Doc : Java文档

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. 返回一个Field对象数组,该数组反映由该Class对象表示的类或接口声明的所有字段。 This includes public, protected, default (package) access, and private fields, but excludes inherited fields. 这包括公共,受保护,默认(程序包)访问和私有字段, 但不包括继承的字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM