Generics and Class<? extends Enum<?>>, EnumSet.allOf(class) vs class.getEnumConstants()

前端 未结 2 2187
自闭症患者
自闭症患者 2021-02-19 15:29

I have the following BeanValidation code that works fine, and permits to validate that a bean annotated with:

  @EnumValue(enumClass = MyTestEnum.class)
  privat         


        
2条回答
  •  孤独总比滥情好
    2021-02-19 16:02

    My guess is that in ? extends Enum the two ? could be different whereas allOf expects a T extends Enum where both T are the same.

    For example, consider the following code:

    static enum MyEnum {}
    static class EnumValue> {
        Class enumClass;
        EnumValue(Class enumClass) {
            this.enumClass = enumClass;
        }
        Class enumClass() { return enumClass; }
    }
    

    These lines will compile:

    EnumValue enumValue = new EnumValue(MyEnum.class); // raw constructor
    Set> enumInstances = EnumSet.allOf(enumValue.enumClass());
    

    because we know that the two T in enumValue.enumClass() are the same but this won't:

    EnumValue enumValue = new EnumValue(MyEnum.class);
    Class> enumSelected = enumValue.enumClass();
    Set> enumInstances = EnumSet.allOf(enumSelected);
    

    because you have lost information by using a Class> as an intermediate step.

提交回复
热议问题