All Downloads are FREE. Search and download functionalities are using the official Maven repository.

pageobjectapi.PageObjectApiFactory Maven / Gradle / Ivy

package pageobjectapi;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class PageObjectApiFactory {
    private final Map>, PageObjectApi>> pageObjectCache = new HashMap<>();

    public > T createPageObject(Map map, Class pageObjectClass) {
        PageObjectApi> cachePageObject = pageObjectCache.get(pageObjectClass);

        if (cachePageObject != null) {
            return pageObjectClass.cast(cachePageObject);

        } else {
            try {
                Class> superClass = (Class>) pageObjectClass.getSuperclass();
                Constructor constructor = pageObjectClass.getDeclaredConstructor(superClass);
                constructor.setAccessible(true);
                T instance = constructor.newInstance();

                Field field = superClass.getDeclaredField("map");
                field.setAccessible(true);
                field.set(instance, new HashMap<>(map));

                pageObjectCache.put(pageObjectClass, instance);
                return instance;

            } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchFieldException | NoSuchMethodException e) {
                e.printStackTrace();

                throw new PageNotInitializedException("Не удалось инициализировать " + pageObjectClass.getClass().getName());
            }
        }
    }

    static class PageNotInitializedException extends RuntimeException {
        PageNotInitializedException(String message) {
            super(message);
        }
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy