我有正常工作,並允許以下BeanValidation代碼來驗證帶註釋一個bean:泛型和類<?擴展Enum <?>>,EnumSet.allOf(類)與class.getEnumConstants()
@EnumValue(enumClass = MyTestEnum.class)
private String field;
public enum MyTestEnum {
VAL1, VAL2;
}
將只驗證如果字段值是「VAL1」或「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);
}
}
}
我不明白的是爲什麼我的第一次嘗試失敗。使用替代enumSelected.getEnumConstants()
以下代碼上面:
Set<? extends Enum<?>> enumInstances = EnumSet.allOf(enumSelected);
的IntelliJ 12不突出任何錯誤,但是編譯器說:
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<?>>
我不明白的問題,我也有代碼的正常工作:
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;
}
相關門票:http://stackoverflow.com/questions/5548091/problem-when-trying-to-use-generics – 2013-03-12 16:38:31
這一個太:http://stackoverflow.com/questions/3546745/multiple-wildcards-on-一個泛型米ethods-makes-java-compiler-and-me-very-confu – assylias 2013-03-12 16:39:41
@ChristopheRoussy:Ticket?現在StackOverflow是一個支持系統:) – mellamokb 2013-03-12 16:52:32