简体   繁体   中英

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 (eg Fish.class or Salmon.class ) in which I call ?

One option is adding an abstract method that is overridden in the subclass to return the right class type:

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

Another option is introducing an instance variable.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM