在创建每个类型必须属于同一个父 class 的类型集合时如何强制执行类型安全?

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

问题总结

我想存储一个对象类型列表,但规定所有类型都是特定父 class 的子class。例如像下面这样的东西:

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

问题是我想定义 listOfChildClassTypes 列表,以便只能将 ParentClass 的子类型添加到其中 - 任何尝试添加不是 ParentClass 的子class 的类型的尝试应该会导致编译器错误。通过使用泛型 'Type' class,上面的代码允许将任何类型存储在需要运行时验证来检查的列表中。我想避免这种情况。

感谢您的帮助。

您应该阅读什么是 PECS 以及什么是“有界类型”,因为这正是您在这里需要的:

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