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

后端 未结 2 1366
無奈伤痛
無奈伤痛 2021-02-19 13:11

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 13:49

    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.

提交回复
热议问题