Generic method return type

Posted on 2013-10-30 17:14  chayu3  阅读(146)  评论(0编辑  收藏  举报

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));}