How do I make the method return type generic?

前端 未结 19 2663
無奈伤痛
無奈伤痛 2020-11-22 06:16

Consider this example (typical in OOP books):

I have an Animal class, where each Animal can have many friends.
And subclasses like

19条回答
  •  耶瑟儿~
    2020-11-22 06:26

    There are a lot of great answers here, but this is the approach I took for an Appium test where acting on a single element can result in going to different application states based on the user's settings. While it doesn't follow the conventions of OP's example, I hope it helps someone.

    public  T tapSignInButton(Class type) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
        //signInButton.click();
        return type.getConstructor(AppiumDriver.class).newInstance(appiumDriver);
    }
    
    • MobilePage is the super class that the type extends meaning you can use any of its children (duh)
    • type.getConstructor(Param.class, etc) allows you to interact with the constructor of the type. This constructor should be the same between all expected classes.
    • newInstance takes a declared variable that you want to pass to the new objects constructor

    If you don't want to throw the errors you can catch them like so:

    public  T tapSignInButton(Class type) {
        // signInButton.click();
        T returnValue = null;
        try {
           returnValue = type.getConstructor(AppiumDriver.class).newInstance(appiumDriver);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnValue;
    }
    

提交回复
热议问题