Skip to content
Advertisement

How to return list of different Classes sharing the same parent in Java?

I am looking for a small help with my piece of code trying to return list of classes which share the same parent abstract class / interface. Here is the code snippet:

public <T extends Animal> List<Class<T>> getAnimalTypes() {
    return Arrays.<T>asList(Dog.class, Cat.class, Bear.class);
}

Dog, Cat and Bear are classes that extends abstract class Animal. What am I missing ? Thanks, Ondrej,

Advertisement

Answer

To define a method that returns a list of Class objects with the same parent abstract class/interface, specify the return type List<Class<? extends Animal>> to that method:

 public List<Class<? extends Animal>> getAnimalTypes() {
   return Arrays.asList(Dog.class, Cat.class, Bear.class);
 }

That says to the compiler to require a type of class that extends the class Animal. There is no need to specify the generic type T.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement