Question

I currently am writing this function:

public WebElementList findWebElementList(final By by){
    return new WebElementList((List<WebElement>) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class<?>[] { List.class }, new InvocationHandler() {
        // Lazy initialized instance of WebElement
        private List<WebElement> webElements;

        public Object invoke(Object proxy, Method method, Object[] args)
                throws Throwable {
            if (webElements == null) {
                webElements = findElements(by);
            }
            return method.invoke(webElements, args);
        }
    }), driver);
}

It is throwing an unchecked cast from Object to List. I have used a proxy around WebElement, and it doesn't...so I believe that is caused by List being a generics class.

Is there any way for me to have a proxy around a List, and not get that unchecked cast warning?

Was it helpful?

Solution

The method Proxy.newProxyInstance returns an Object. Since you know that this object will be always a List<WebElement>, you cast it to this type. In that case, Java cannot guess that this will be OK and shows you a warning. This could possibly throws an exception at runtime if this was not the case.

But here, since you know that won't throw any exception at runtime, you can get ride of this warning by adding a @SuppressWarnings("unchecked") annotation to let Java know that you are aware of this unchecked/unsafe cast.

You would do something like this:

public WebElementList findWebElementList(final By by){
   @SuppressWarnings("unchecked")
   return new WebElementList((List<WebElement>) Proxy.newProxyInstance(...

There is a good explanation of this @SuppressWarnings from Jon Skeet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top