【发布时间】:2015-01-26 09:18:40
【问题描述】:
我想写一个可以像new EnumConverter(MyEnum.class);这样使用的泛型类
但是我必须编写那个类,以便它与对enum.values() 的通用调用一起工作?
public class EnumConverter {
public EnumConverter(Class<Enum<?>> type) {
this.type = type;
}
public EnumConverter convert(String text) {
//error: Type mismatch: cannot convert from element type capture#1-of ? to Enum<?>
for (Enum<?> candidate : type.getDeclaringClass().getEnumConstants()) {
if (candidate.name().equalsIgnoreCase(text)) {
return candidate;
}
}
}
}
【问题讨论】:
-
this.type是什么类型;它是如何声明的?
-
您的转换方法有问题,因为它应该返回
EnumConverter而candidate的类型是Enum<?>!! -
我认为是构造函数
-
我绝对不清楚问题是什么。
-
好问题。这是相关的,但不同:stackoverflow.com/questions/4014117/…(请不要将此评论视为“嘿,这个问题是骗子!”)