【问题标题】:How to return Generic type from same method for parent and child classes如何从父类和子类的相同方法返回泛型类型
【发布时间】:2014-11-25 20:35:26
【问题描述】:

这是我的场景 我有 3 节课。

class Animal {
   public getWeight(){ ..... }
   public getHeight(){ ..... }
}

class Dog extends Animal {
   public getDogType() { ...}
}

class Cat extends Animal {
   public getCatType(){....}
}

还有一个不同的方法,它返回一个以 Object 作为参数的 Animal 类型

public Animal translate(CustomObject o){
     ... so many calculations here
}

这里 translate 方法返回 Animal 对象,但是我需要使用相同的方法来返回 Dog 和 Cat 类型,而不需要进行类型转换。我知道我必须在这里使用泛型,但是如何编辑 translate 方法以支持泛型,以便我可以将 Class 类型传递给它的参数,如果使用 Cat 参数调用它返回 Cat 对象,如果使用 Animal 参数和 Dog 调用它返回 Animal 对象如果使用 Dog 参数调用对象。

例如:- Cat newCat = translate(object, Cat.class); //should return cat object and not animal obj 而不是

Cat newCat = (Cat)translate(object, Cat.class)

谢谢。

【问题讨论】:

    标签: java generics polymorphism


    【解决方案1】:

    你需要一个自引用绑定:

    class Animal<T extends Animal<T>> {
       public getWeight(){ ..... }
       public getHeight(){ ..... }
       public T translate(CustomObject o){
         //... so many calculations here
       }
    }
    
    class Dog extends Animal<Dog> {
       //
    }
    
    class Cat extends Animal<Cat> {
       //
    }
    

    您可以考虑将translate() 抽象化,允许子类处理它们自己的实现。

    【讨论】:

    • 感谢您的回答
    • np。仅供参考,其他答案允许您从 Dog 对象返回 Cat
    【解决方案2】:

    试试public &lt;T extends Animal&gt; translate(CustomObject o, Class&lt;T&gt; clazz)

    【讨论】:

    • 感谢您的回答
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-14
    • 2016-12-24
    • 1970-01-01
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多