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));}
  • 相关阅读:
    常用jquery
    常用记录
    mysql proxy 读写分离
    Linux 学习笔记
    php 1116
    php 1115
    php 1110
    php 1109
    php 1108
    php 1105
  • 原文地址:https://www.cnblogs.com/chayu3/p/3397322.html
Copyright © 2011-2022 走看看