mercredi 1 avril 2020

Java generic type : how to pass the right class type properly?

I have an abstract class like this :

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); 
   }
}

and a child class :

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

and a grandchild class:

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

I think there is a design problem of this heritage. But how can I achieve that when I call callAPI() (in either FishService or SalmonService), I am able to pass the exact class type (e.g. Fish.class or Salmon.class) in which I call ?

Aucun commentaire:

Enregistrer un commentaire