Generic method return type

2022-10-25,,,

Here's the Animal class:

public class Animal{

private Map<String,Animal> friends =new HashMap<String,Animal>();

public void addFriend(String name,Animal animal){
friends.put(name,animal);
} public Animal callFriend(String name)
{return friends.get(name);}}

And here's some code snippet with lots of typecasting:

Mouse jerry =newMouse();
jerry.addFriend("spike",newDog());
jerry.addFriend("quacker",newDuck());
((Dog) jerry.callFriend("spike")).bark();
((Duck) jerry.callFriend("quacker")).quack();

Is there any way I can use generics for the return type to get rid of the typecasting, so that I can say

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

Here's some initial code with return type conveyed to the method as a parameter that's never used.

public<T extendsAnimal> T callFriend(String name, T unusedTypeObj){return(T)friends.get(name);}

Answer==
public<T extendsAnimal> T callFriend(String name,Class<T> type){return type.cast(friends.get(name));}

Generic method return type的相关教程结束。

《Generic method return type.doc》

下载本文的Word格式文档,以方便收藏与打印。