Java-从对象中获取具有公共超类的字段列表

时间:2019-03-07 15:47:07

标签: java reflection

我想从对象中获取具有公共超类的字段列表,然后对其进行迭代并执行超类中现有的方法。 示例:

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方法,该方法应该解析页面的字段列表,然后获取具有超类baseElement的字段的列表,然后对于每个启动方法都存在。 我确认这不是反射私有字段的重复

1 个答案:

答案 0 :(得分:2)

以下代码应该可以实现您所期望的。我已经在注释中标记了代码的功能及其工作方式。

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
}