Java – generics and classes Extended enumeration > >, EnumSet. allOf(class)vs class. getEnumConstants()
•
Java
I have the following beanvalidation code that works properly and allows you to validate a bean annotation with:
@EnumValue(enumClass = MyTestEnum.class)
private String field;
public enum MyTestEnum {
VAL1,VAL2;
}
It is validated only when the field value is "val1" or "val2"
public class EnumNameValidator implements ConstraintValidator<EnumValue,String> {
private Set<String> AVAILABLE_ENUM_NAMES;
@Override
public void initialize(EnumValue enumValue) {
Class<? extends Enum<?>> enumSelected = enumValue.enumClass();
Set<? extends Enum<?>> enumInstances = Sets.newHashSet(enumSelected.getEnumConstants());
AVAILABLE_ENUM_NAMES = FluentIterable
.from(enumInstances)
.transform(PrimitiveGuavaFunctions.ENUM_TO_NAME)
.toImmutableSet();
}
@Override
public boolean isValid(String value,ConstraintValidatorContext context) {
if ( value == null ) {
return true;
} else {
return AVAILABLE_ENUM_NAMES.contains(value);
}
}
}
What I don't understand is why my first attempt failed Use enumselected instead of the following code getEnumConstants():
Set<? extends Enum<?>> enumInstances = EnumSet.allOf(enumSelected);
IntelliJ 12 does not highlight any errors, but the compiler says:
java: method allOf in class java.util.EnumSet<E> cannot be applied to given types;
required: java.lang.Class<E>
found: java.lang.Class<capture#1 of ? extends java.lang.Enum<?>>
reason: inferred type does not conform to declared bound(s)
inferred: capture#1 of ? extends java.lang.Enum<?>
bound(s): java.lang.Enum<capture#1 of ? extends java.lang.Enum<?>>
I don't understand the problem. I also have that code working normally:
private static <T extends Enum<T> & EnumAlternativeName> T safeGetByAlternativeName(Class<T> enumClass,String alternativeName) {
for ( T t : EnumSet.allOf(enumClass) ) {
if ( t.getAlternativeName().equals(alternativeName) ) {
return t;
}
}
return null;
}
Solution
Is my guess? Extended enum where t is 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 compile:
EnumValue<?> enumValue = new EnumValue(MyEnum.class); // raw constructor Set<? extends Enum<?>> enumInstances = EnumSet.allOf(enumValue.enumClass());
Because we know these two are in enumvalue The T in enumclass () is the same, but this does not:
EnumValue enumValue = new EnumValue(MyEnum.class); Class<? extends Enum<?>> enumSelected = enumValue.enumClass(); Set<? extends Enum<?>> enumInstances = EnumSet.allOf(enumSelected);
Because you have used class > as an intermediate step
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
