zoukankan      html  css  js  c++  java
  • Generic method return type

    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));}
  • 相关阅读:
    Spring第一次测试错题解析
    正则回顾
    Spring经典---AOP
    动态代理
    MyBatis第一次测试卷---错题分析
    JS中对数组元素进行增删改移
    限制条件补全代码系列题
    字符串去空格
    数组去重
    数组排序
  • 原文地址:https://www.cnblogs.com/chayu3/p/3397322.html
Copyright © 2011-2022 走看看