gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 01:37:18 26 4
gpt4 key购买 nike

我想从对象中获取具有公共(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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com