mercredi 27 mai 2015

Creating proxys in java for Lists (selenium)

Im trying to use Java Proxy to override classes from Selenium, with which I work. Sometimes its working, but sometimes my code can not recognize public constructors.

I have the following classes:

public class ElementListHandler implements InvocationHandler {

private final ElementLocator locator;
private final Class<?> wrappingType;

public <T> ElementListHandler(Class<T> interfaceType, 
                               ElementLocator locator)  {

    this.locator = locator;

    //method that get the Class type, which implements the interface.
    //This is done, because in the normal Selenium Evironment, 
    //creates proxys, that will be of type RemoteWebElement
    //and I want proxy of Wrap classes I wrote (e.g. TileImpl)
    this.wrappingType = 
        ImplementedByProcessor.getWrapperClass(interfaceType);

}

@Override
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
    List<Object> wrappingList = new ArrayList<Object>();
    Constructor<?> cons = wrappingType.getConstructor(WebElement.class);

    for (WebElement element : locator.findElements()) {
        Object thing = cons.newInstance(element);
        wrappedList.add(wrappingType.cast(thing));
    }
    try {return method.invoke(wrappedList, objects);
    } catch (InvocationTargetException e) {throw e.getCause();}
}
}

Here the proxy is generated:

protected <T> List<T> proxyForListLocator(ClassLoader loader, Class<T> interfaceType, ElementLocator locator) {
    InvocationHandler handler = new ElementListHandler(interfaceType, locator);

    List<T> proxy = (List<T>) Proxy.newProxyInstance(loader, new Class[]
                     {List.class, interfaceType}, handler);
    return proxy;
}

Sometimes it works, sometimes not. I have following class structure:

--Interface IElement extends WebElement --class Element implement IElement

--Interface ITile extends ISubPage extends WebElement --class Tile extends SubPage implements ITile

Both Element and Tile have WebElement type as parameter for their constructur. But List does receive proxy from my method, and List does not.

I get the error:

java.lang.reflect.UndeclaredThrowableException
    at $Proxy8.iterator(Unknown Source)

And as I put break points to debug, the handler in both cases has the attribute wrappingType, but in the case of ITIle, there are not declared or undeclared constructors recognize, although the constructor is public

Any idea?





Aucun commentaire:

Enregistrer un commentaire