mardi 16 janvier 2018

Java reflections method get another method with annotation

I am using Cucumber with Selenide for my UI tests and I have these methods

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);
}

I am very new to reflections and am trying to build a page objects pattern utilising the org.reflections.Reflections library to search for annotated fields in various page object classes. I am, however, having problems returning the SelenideElement from the field I'm getting in the second method (line SelenideElement el = ... is plain wrong at the moment). How do I get the field I can use as a SelenideElement (with @ElementTitle and @FindBy annotations) in my test? Thanks in advance.





Aucun commentaire:

Enregistrer un commentaire