Java - 从对象获取具有公共(public)父类(super class)的字段列表

标签 java reflection

我想从对象中获取具有公共(public)父类(super class)的字段列表,然后迭代它们并执行父类(super class)中存在的方法。 示例:

class BasePage{
***public void check(){}***
}

class Page extends BasePage{
    private TextElement c;
    private ButtonElement e;

    //methods acting on c and e
}

class TextElement extends BaseElement {

}

class ButtonElement extends BaseElement {

}

class BaseElement {
    public void exits(){};
}

因此,我想从 BasePage 类实现 check 方法,该方法应该解析页面的字段列表,然后获取具有父类(super class) baseElement 的字段列表,然后为每个启动存在的方法。 我确认它不是反射私有(private)字段的重复

最佳答案

下面的代码应该能达到您的预期。我已经在注释中标记了代码的作用以及它是如何工作的。

public static void main(String[] args) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException {
    Page page = new Page();
    Collection<Field> fields = getFieldsWithSuperclass(page.getClass(), BaseElement.class);
    for(Field field : fields) { //iterate over all fields found
        field.setAccessible(true);
        BaseElement fieldInstance = (BaseElement) field.get(pageCreated); //get the instance corresponding to the field from the given class instance
        fieldInstance.exists(); //call the method
    }
}

private static Collection<Field> getFieldsWithSuperclass(Class instance, Class<?> superclass) {
    Field[] fields = instance.getDeclaredFields(); //gets all fields from the class

    ArrayList<Field> fieldsWithSuperClass = new ArrayList<>(); //initialize empty list of fields
    for(Field field : fields) { //iterate over fields in the given instance
        Class fieldClass = field.getType(); //get the type (class) of the field
        if(superclass.isAssignableFrom(fieldClass)) { //check if the given class is a super class of this field
            fieldsWithSuperClass.add(field); //if so, add it to the list
        }
    }
    return fieldsWithSuperClass; //return all fields which have the fitting superclass
}

关于Java - 从对象获取具有公共(public)父类(super class)的字段列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55047767/

相关文章:

java - 是否可以在 Windows XP 中开发微秒级时间精度的实时数据采集系统?

java - 不使用反射访问类的字段?

reflection - 如何从 Case 实例中获取 Discriminated Union Type?

java - JAVA 6 中出现 SSL 异常,但 JAVA 8 中没有 SSL 异常

java - 如何选择要在 Builder 类中使用的函数类型?

java - 如何将本地日期与本地日期列表进行比较

c# - .NET 通过反射获取私有(private)属性

java - 在 Javascript 中出现 "org.mozilla.javascript.Undefined@c91f0d"这个错误

c# - 声明一个类引用列表

java - 从类型为 "Class<?>"的对象启动 main 方法