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

前端 未结 1 955
花落未央
花落未央 2021-02-19 17:35

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

  @EnumValue(enumClass = MyTestEnum.class)
  privat         


        
相关标签:
1条回答
  • 2021-02-19 17:48

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

    For example, consider the following code:

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

    These lines will compile:

    EnumValue<?> enumValue = new EnumValue(MyEnum.class); // raw constructor
    Set<? extends Enum<?>> 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<? extends Enum<?>> enumSelected = enumValue.enumClass();
    Set<? extends Enum<?>> enumInstances = EnumSet.allOf(enumSelected);
    

    because you have lost information by using a Class<? extends Enum<?>> as an intermediate step.

    0 讨论(0)
提交回复
热议问题