Java 将带注释的字段获取为 SelenideElement 的反射方法

Java reflections method to get annotated field as SelenideElement

我在 UI 测试中使用 Cucumber 和 Selenide,我有这些方法

public static void initPage(String pageName) throws Exception {
    Set<Class<?>> annotated = new Reflections(PAGES_PACKAGE).getTypesAnnotatedWith(PageTitle.class);

    for (Class classToInit : annotated) {
        PageTitle annotation = (PageTitle) classToInit.getAnnotation(PageTitle.class);
        if (annotation.name().equals(pageName)) {
            classToInit.newInstance();
            lastInitialized = substringAfter(classToInit.toString(), "class ");
            lastInitClass = classToInit;
            return;
        }
    }

    throw new AutotestError("Could not find page to init: " + pageName);
}

public static SelenideElement findElementByTitle(String elementName) throws IllegalAccessException, InstantiationException {
    Set<Field> annotated = new Reflections(lastInitialized, new FieldAnnotationsScanner()).getFieldsAnnotatedWith(ElementTitle.class);

    for (Field field : annotated) {
        ElementTitle annotation = field.getAnnotation(ElementTitle.class);
        if (annotation.name().equals(elementName)) {
            field.setAccessible(true);
            SelenideElement el = (SelenideElement) field
            return el;
        }
    }
    throw new AutotestError("Element not found: " + elementName);
}

我对反射还很陌生,我正在尝试利用 org.reflections.Reflections 库构建页面对象模式,以在各种页面对象 类 中搜索带注释的字段。但是,我在从第二种方法中获得的字段返回 SelenideElement 时遇到问题(行 SelenideElement el = ... 目前完全错误)。如何在我的测试中获取可用作 SelenideElement(带有 @ElementTitle 和 @FindBy 注释)的字段?提前致谢。

你应该换行
SelenideElement el = (SelenideElement) field

SelenideElement el = ((SelenideElement) field.get(pageObject))

说明

根据 Field.get 的文档:
Returns指定对象上此Field表示的字段的值。如果值具有基本类型,则该值会自动包装在对象中。

我已经修改了有问题的代码行,如下所示:

SelenideElement el = (SelenideElement) field.get(page(lastInitClass);

其中 page() 是 com.codeborne.selenide.Selenide.page,如果我理解正确的话,它是 Selenium pageFactory 的 Selenide 包装器。