简体   繁体   中英

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'?

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. Java-Doc :

Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object. This includes public, protected, default (package) access, and private fields, but excludes inherited fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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