How do I make the method return type generic?

前端 未结 19 2656
無奈伤痛
無奈伤痛 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:32

    You could define callFriend this way:

    public  T callFriend(String name, Class type) {
        return type.cast(friends.get(name));
    }
    

    Then call it as such:

    jerry.callFriend("spike", Dog.class).bark();
    jerry.callFriend("quacker", Duck.class).quack();
    

    This code has the benefit of not generating any compiler warnings. Of course this is really just an updated version of casting from the pre-generic days and doesn't add any additional safety.

提交回复
热议问题