How do I make the method return type generic?

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

    This question is very similar to Item 29 in Effective Java - "Consider typesafe heterogeneous containers." Laz's answer is the closest to Bloch's solution. However, both put and get should use the Class literal for safety. The signatures would become:

    public  void addFriend(String name, Class type, T animal);
    public  T callFriend(String name, Class type);
    

    Inside both methods you should check that the parameters are sane. See Effective Java and the Class javadoc for more info.

提交回复
热议问题