Are Doge and Yeti extending the same Animal class? If yes then you could do
public AnimalGroup<? extends Animal> getAnimalGroup (String animalName) {
Class<? extends Animal> animalClass = Doge.class;
if("Yetti".equals(animalName)) {
animalClass = Yetti.class;
}
AnimalGroup<? extends Animal> animalGroup = new AnimalGroup<>(animalClass);
animalGroup.doSomeProcessing();
return animalGroup;
}
If they not, then well, they should :)
I cannot really understand the edit I did a POC and the following code works (assuming interface A and implementing classes B and C:
private static List<? extends A> generateObjects(boolean isItB) {
if (isItB) {
return new ArrayList<B>() {
{
add(new B());
}
};
} else {
return new ArrayList<C>() {
{
add(new C());
}
};
}
}
private static void consumeObjects(List<? extends A> consuming) {
for (A a : consuming) {
a.doStuff();
}
}
public static void main(String[] args) {
List<? extends A> generatedBs = generateObjects(false);
consumeObjects(generatedBs);
}