如何从父类和子类的相同方法返回泛型类型 [英] How to return Generic type from same method for parent and child classes

查看:126
本文介绍了如何从父类和子类的相同方法返回泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  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 of

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

Thanks.

解决方案

Try public <T extends Animal> translate(CustomObject o, Class<T> clazz).

这篇关于如何从父类和子类的相同方法返回泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆