如何从父类和子类的相同方法返回泛型类型 [英] How to return Generic type from same method for parent and child classes
问题描述
class Animal {
public getWeight (){.....}
public getHeight(){.....}
}
class Dog extends Animal {
public getDogType() {...}
}
class Cat extends Animal {
public getCatType(){....}
}
$ b另外还有一个方法返回一个以Object为参数的Animal类型
public Animal translate(CustomObject o){
...很多计算在这里
}
这里translate方法返回Animal Object,但我需要使用相同的方法来返回Dog和Cat类型,而不使用类型转换。我知道我必须在这里使用泛型,但是如何编辑translate方法来支持Generics,以便我可以将Class类型传递给它的参数,并且如果使用Cat参数和Animal对象调用,则使用Animal参数和Dog调用时返回Cat对象如果使用Dog参数调用该对象。
例如: -
Cat newCat = translate(object,Cat.class); // cat应该返回cat对象而不是动物obj
而不是
Cat newCat =(Cat)translate(object,Cat。 class)
谢谢。
解决方案试试
public< T extends Animal> translate(CustomObject o,Class< T> clazz)
。Here is my scenario I've 3 classes.
class Animal { public getWeight(){ ..... } public getHeight(){ ..... } } class Dog extends Animal { public getDogType() { ...} } class Cat extends Animal { public getCatType(){....} }
And there is a different method which returns an Animal type taking an Object as a parameter
public Animal translate(CustomObject o){ ... so many calculations here }
Here translate method returns Animal Object, but I need to use the same method to return Dog and Cat types too without typecasting. I know I have to use Generics here but how can I edit translate method to support Generics, so that I can pass the Class type to its parameter and it returns Cat object if called using Cat parameter and Animal object if called using Animal parameter and Dog object if called using Dog parameter.
eg:-
Cat newCat = translate(object, Cat.class); //should return cat object and not animal obj
instead ofCat newCat = (Cat)translate(object, Cat.class)
Thanks.
解决方案Try
public <T extends Animal> translate(CustomObject o, Class<T> clazz)
.这篇关于如何从父类和子类的相同方法返回泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文