如何使方法返回类型通用?

时光总嘲笑我的痴心妄想 提交于 2020-10-23 09:16:47

问题:

Consider this example (typical in OOP books): 考虑以下示例(OOP书籍中的典型示例):

I have an Animal class, where each Animal can have many friends. 我有一个Animal课,每个Animal可以有很多朋友。
And subclasses like Dog , Duck , Mouse etc which add specific behavior like bark() , quack() etc. 还有子类,如DogDuckMouse等,它们添加了特定的行为,如bark()quack()等。

Here's the Animal class: 这是Animal类:

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

    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 = new Mouse();
jerry.addFriend("spike", new Dog());
jerry.addFriend("quacker", new Duck());

((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 extends Animal> T callFriend(String name, T unusedTypeObj){
    return (T)friends.get(name);        
}

Is there a way to figure out the return type at runtime without the extra parameter using instanceof ? 有没有一种方法可以使用instanceof在运行时确定返回类型而无需额外的参数? Or at least by passing a class of the type instead of a dummy instance. 或者至少通过传递类型的类而不是虚拟实例。
I understand generics are for compile time type-checking, but is there a workaround for this? 我了解泛型用于编译时类型检查,但是是否有解决方法?


解决方案:

参考一: https://stackoom.com/question/1tH5/如何使方法返回类型通用
参考二: https://oldbug.net/q/1tH5/How-do-I-make-the-method-return-type-generic
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!