How do I make the method return type generic?

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

    You could implement it like this:

    @SuppressWarnings("unchecked")
    public  T callFriend(String name) {
        return (T)friends.get(name);
    }
    

    (Yes, this is legal code; see Java Generics: Generic type defined as return type only.)

    The return type will be inferred from the caller. However, note the @SuppressWarnings annotation: that tells you that this code isn't typesafe. You have to verify it yourself, or you could get ClassCastExceptions at runtime.

    Unfortunately, the way you're using it (without assigning the return value to a temporary variable), the only way to make the compiler happy is to call it like this:

    jerry.callFriend("spike").bark();
    

    While this may be a little nicer than casting, you are probably better off giving the Animal class an abstract talk() method, as David Schmitt said.

提交回复
热议问题