Ho il seguente codice BeanValidation che funziona bene, e permette di convalidare che un fagiolo annotato con:Generici e Classe <? si estende Enum <?>>, EnumSet.allOf (classe) vs class.getEnumConstants()
@EnumValue(enumClass = MyTestEnum.class)
private String field;
public enum MyTestEnum {
VAL1, VAL2;
}
saranno convalidati solo se il valore del campo è "VAL1" o "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);
}
}
}
Quello che non capisco è il motivo per cui il mio primo tentativo non è riuscito. Utilizzando invece del enumSelected.getEnumConstants()
sopra il seguente codice:
Set<? extends Enum<?>> enumInstances = EnumSet.allOf(enumSelected);
Intellij 12 non evidenzia alcun errore, ma il compilatore dice:
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<?>>
non capisco il problema, e ho anche che il codice che funziona bene:
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;
}
Biglietto correlato: http://stackoverflow.com/questions/5548091/problem-when-trying-to-use-generics –
Anche questo: http://stackoverflow.com/questions/3546745/multiple-wildcards-on- a-generic-m ethods-makes-java-compiler-and-me-very-confu – assylias
@ChristopheRoussy: biglietto? StackOverflow è un sistema di supporto ora :) – mellamokb