【问题标题】:Java - Getting a list of fields that have a common super class from an objectJava - 从对象中获取具有公共超类的字段列表
【发布时间】:2019-07-29 13:47:00
【问题描述】:

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

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 的字段列表,然后对于每个启动该方法都存在。 我确认它不是反射私有字段的副本

【问题讨论】:

标签: java reflection


【解决方案1】:

以下代码应该符合您的预期。我已经标记了代码的作用以及它在 cmets 中的工作方式。

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.lang.IllegalAccessException : Object fieldInstance = field.get(pageCreated);
  • 我添加了一个更新来修复 IllegalAccessException。谢谢伊恩·雷温克尔
猜你喜欢
  • 2016-07-19
  • 1970-01-01
  • 1970-01-01
  • 2023-02-17
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
  • 1970-01-01
  • 2017-06-09
相关资源
最近更新 更多