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

前端 未结 2 1026
悲哀的现实
悲哀的现实 2021-02-19 15:21

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 15:55

    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.

提交回复
热议问题