Search code examples
javatypescollectionssubclasstype-safety

How to enforce type-safety when creating a collection of types where each type must belong to the same parent class?


Summary of the problem

I would like to store a list of object types but stipulate that all the types are subclasses of a particular parent class. For example something like the following:

public abstract class ParentClass {
    ...

}

public class ChildClass1 extends ParentClass {
    ...

}

public class ChildClass2 extends ParentClass {
    ...

}

public class SomeOtherClass {
    List<Type> listOfChildClassTypes = new ArrayList<>();

    public void someMethod() {
        listOfChildClassTypes.add(ChildClass1.class);
        listOfChildClassTypes.add(ChildClass2.class);
    }
}

The problem is that I would like to define the listOfChildClassTypes list such that only sub-types of ParentClass can be added to it - any attempt to add a type that is not a sub-class of ParentClass should result in a compiler error. By using the generic 'Type' class, the code above allows any type to be stored in the list which will require runtime validation to check. This I would like to avoid.

Thanks for your help.


Solution

  • You should read what PECS is and what "bounded types" are, because that is exactly what you need here :

    List<Class<? extends ParentClass>> listOfChildClassTypes = new ArrayList<>();