jeudi 14 juin 2018

Cannot find classes in a package using Class.forName()

Using Java I am implementing a Page Factory object for selenium testing that takes the name of a page object and instantiates it through reflection for use by Cucumber step definitions. The problem I am having is that the code below cannot find the declared class. Both the object PageFactory which contains this code and the page object LoginPage reside in a package called pages.

 /**
 * This method take a string containing a Page Object class name (case-sensitive) and returns an instance of the Page Object.
 * This allows us to operate on pages without knowing they exist when we write step definitions.
 * @param choice String
 * @return Page Object cast as a Page
 */
public static Page getPage(String choice) {
    Page entity = null;

    try {
        entity = (Page) Page.forName(choice).newInstance();
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    return entity;
}

I receive a stack trace with java.lang.ClassNotFoundException: LoginPage as the beginning of the error. If I change the entity creation to the following code, then it works.

        private static String packageName = "pages";
        entity = (Page) Page.forName(packageName + "." + choice).newInstance();

The problem is that I want to organize my pages. When I create pages.mywebsite and place LoginPage within that, PageFactory won't know where to find the file.

Leaving aside the problem that I could have two namespaces pages.mywebsite and pages.myotherwebsite that both have a LoginPage object, how can I find the files I want without declaring the exact package, and just say "Look in this package and the ones below for the class"?





Aucun commentaire:

Enregistrer un commentaire