How do I make the method return type generic?

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

    As you said passing a class would be OK, you could write this:

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

    And then use it like this:

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

    Not perfect, but this is pretty much as far as you get with Java generics. There is a way to implement Typesafe Heterogenous Containers (THC) using Super Type Tokens, but that has its own problems again.

提交回复
热议问题