gpt4 book ai didi

Java泛型类型: how to pass the right class type properly?

转载 作者:行者123 更新时间:2023-12-02 08:47:47 25 4
gpt4 key购买 nike

我有一个像这样的抽象类:

public abstract class AnimalService<T extends Animal> {
...
public T callAPI() {
// here the Class<T> can be Fish.class or Salmon.class or any child class type of Animal
return restTemplate.getForObject(url, Class<T>, params);
}
}

和一个子类:

public class FishService<T extends Fish> extends AnimalService<Fish> {
...
}

和一个孙子类:

public class SalmonService extends FishAnimalService<Salmon> {
...
}

我认为这个传承存在设计问题。但是,当我调用 callAPI() (在 FishServiceSalmonService 中)时,我怎样才能实现这一点,我能够传递准确的 类类型(例如Fish.classSalmon.class),我在其中调用?

最佳答案

一种选择是添加一个在子类中重写的抽象方法以返回正确的类类型:

public abstract class AnimalService<T extends Animal> {
public T callAPI() {
return restTemplate.getForObject(url, getAnimalClass(), params);
}
abstract Class<T> getAnimalClass();
}

public class SalmonService extends FishAnimalService<Salmon> {
Class<Salmon> getAnimalClass() {
return Salmon.class;
}
}

另一种选择是引入实例变量。

abstract class AnimalService<T extends Animal> {
private Class<T> animalClass;

protected AnimalService(Class<T> animalClass) {
this.animalClass = animalClass;
}

public T callAPI() {
return restTemplate.getForObject(url, animalClass, params);
}
}

public class FishService<T extends Fish> extends AnimalService<Fish> {
protected FishService(Class<T> fishClass) {
super(fishClass);
}
}


public class SalmonService extends FishAnimalService<Salmon> {
public SalmonService() {
super(Salmon.class);
}
}

关于Java泛型类型: how to pass the right class type properly?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60971322/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com