简体   繁体   English

Java反射 - 从子类和超类中获取字段

[英]Java Reflection - Get Fields From Sub Class as well as Super Class

I am using inherited bean classes for my project. 我正在为我的项目使用继承的bean类。 Here some of super classes will be empty and sub class can have fields & some of sub classes will be empty and super class can have fields. 这里有些超类是空的,子类可以有字段,有些子类是空的,超类可以有字段。

My requirement is to get all private / public fields from Sub class as well as to get all public / protected fields from Super class too. 我的要求是从Sub类获取所有私有/公共字段以及从Super类获取所有公共/受保护字段。

Below I have tried to achieve it. 下面我试图实现它。 But I failed to meet my requirement. 但我没能达到我的要求。 Please provide some suggestion to achieve this one. 请提供一些建议来实现这一目标。

Field fields [] = obj.getClass().getSuperclass().getDeclaredFields();

If I use above code, I can get only Super class fields 如果我使用上面的代码,我只能获得超类字段

Field fields [] = obj.getClass().getFields();

If I use above code, I can get all fields from Sub class and super class fields 如果我使用上面的代码,我可以从Sub类和超类字段获取所有字段

Field fields [] = obj.getClass().getDeclaredFields();

If I use above code, I can get Sub class public and private all fields. 如果我使用上面的代码,我可以获得Sub类的公共和私有所有字段。

You will have to iterate over all the superclasses of your class, like this: 您将不得不迭代您的类的所有超类,如下所示:

private List<Field> getInheritedPrivateFields(Class<?> type) {
    List<Field> result = new ArrayList<Field>();

    Class<?> i = type;
    while (i != null && i != Object.class) {
        Collections.addAll(result, i.getDeclaredFields());
        i = i.getSuperclass();
    }

    return result;
}

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

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