简体   繁体   中英

Cast a superclass for a generic subclass and add to list

i have a classes like Button, Pane, Checkbox etc.. All of this classes extends from class Element. i have a method

public synchronized  <T extends Element>  List<T> getAllElements() {
   List<WebElement> elements = getDriver().findElements(by);
   List<T> customElements = new ArrayList<>();

   for(int i=0; i<elements.size();i++){
   customElements.add((T) new Element(By.xpath("("+getXpath(by)+")["+i+1+"]")));
}
return customElements;
}    

but i got class cast exception when try to execute List< Button > btns = anybutton.getAllElements();

How to avoid this or solve my problem. Thanks

With the generic method that you have you need to make sure that it always returns the type of objects that your calling code is expecting. The usual pattern to achieve this is to pass the type of object the calling code is expecting in form of Class<T> .

Here is modified version of your code that can guarantee that and avoid runtime ClassCastException .

public static  <T extends Element>  List<T> getAllElements(Class<T> clazz) {
    List<WebElement> elements = getDriver().findElements(by);
    List<T> customElements = new ArrayList<>();

    for(int i=0; i<elements.size();i++){
        T element = null;
        try{
            element = clazz.getConstructor( new Class[]{String.class} ).newInstance( By.xpath("("+getXpath(by)+")["+i+1+"]") );     
        }catch(Exception e){
            //log or handle reflection related exceptions
        }
        customElements.add(element);
    }
    return customElements;
 }   

The above assumes that your Button class has a constructor that takes whatever By.xpath("("+getXpath(by)+")["+i+1+"]") returns. You can of course modify it to work with your actual types. The most important thing here is that there are no casts in here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM