I'm trying to write an AnimalGroup factory class that returns an instance which contains various different types of Animal. Unfortunately i'm being forced to duplicate code due to what seems like Java generics limitations. I've tried every possible combination of wildcards etc that I can think of with no luck.
Here's the code:
public AnimalGroup<?> getAnimalGroup (String animalName) {
if(animalName.equals("Yetti")) {
AnimalGroup<Yetti> animalGroup = new AnimalGroup<>(Yetti.class);
animalGroup.doSomeProcessing();
return animalGroup;
}
else {
AnimalGroup<Doge> animalGroup = new AnimalGroup<>(Doge.class);
animalGroup.doSomeProcessing();
return animalGroup;
}
}
Here's what I want to do:
public AnimalGroup<?> getAnimalGroup (String animalName) {
Class<?> animalClass = Doge.class;
if(animalName.equals("Yetti")) {
animalClass = Yetti.class;
}
AnimalGroup<animalClass> animalGroup = new AnimalGroup<>(animalClass);
animalGroup.doSomeProcessing();
return animalGroup;
}
Update:
Using the <? extends Animal> solution, the following additional processing code no longer works:
// Pseudo-ish code
public <T extends Animal> void setAnimals (T animals) { this.animals = animals; }
List<? extends Animal> animals = getAnimals(animalClass);
animalGroup.setAnimals(animals);
The error given is pretty confusing:
setAnimals(java.util.List<capture<? extends Animal>>) in AnimalGroup cannot be applied to (java.util.List<capture<? extends Animal>>)
Any help much obliged. Thanks! Ben.
<>has to be a type name, it can't be a variable or an expression that resolves to a reference.