今天,一位同事遇到了一个有趣的问题,虽然我认为实际的、宏观的答案是“我们遇到这个问题的事实意味着我们做错了什么”,但我想我还是会问这个。
鉴于以下情况:
public class CrazyEnumTest {
public class EnumeratedThing<T extends Enum<T>> {
public T myValue;
public EnumeratedThing(T value) {
myValue = value;
}
}
public static void main (String[] args) {
String className = args[0];
String enumValue = args[1];
Enum<?> value1 = Enum.valueOf(Class.forName(className), enumValue);
EnumeratedThing<?> thing1 = new EnumeratedThing(value1);
}
}
在调用 Enum.valueOf 时出现以下编译错误:
Bound mismatch: The generic method valueOf(Class, String) of type Enum; 不适用于参数(Class, String)。 推断类型 capture#1-of ? 不是有界参数 >
的有效替代
所以,我的问题是:仅给出枚举类型名称的 String 表示形式以及 .name 是否可以() 其值之一,获取对相应枚举类型对象的引用作为 Enum?
A co-worker ran into an interesting issue today, and while I think the actual, big-picture answer is "the fact that we're having this problem means we're doing something wrong", I figured I'd ask this anyway.
Given the following:
public class CrazyEnumTest {
public class EnumeratedThing<T extends Enum<T>> {
public T myValue;
public EnumeratedThing(T value) {
myValue = value;
}
}
public static void main (String[] args) {
String className = args[0];
String enumValue = args[1];
Enum<?> value1 = Enum.valueOf(Class.forName(className), enumValue);
EnumeratedThing<?> thing1 = new EnumeratedThing(value1);
}
}
I get the following compile error on the call to Enum.valueOf:
Bound mismatch: The generic method valueOf(Class<T>, String) of type Enum<E> is not applicable for the arguments (Class<capture#1-of ?>, String). The inferred type capture#1-of ? is not a valid substitute for the bounded parameter <T extends Enum<T>>
So, my question is: is it possible to, given only the String representation of a enumerated type name as well as the .name() of one of its values, get a reference to the corresponding enumerated type object as an Enum?
发布评论
评论(2)
编译错误告诉您
Class
与Class
。 尝试:请注意,您将收到未经检查的强制转换警告,因此请确保
className
实际上确实代表一个枚举。 您可以通过调用isEnum()
Class
对象上的方法,如下所示:当然,您会在“
new EnumeratedThing(value1)<”上收到原始类型警告/代码>”无论如何。
The compile error is telling you that
Class<?>
is not the same asClass<? extends Enum>
. Try:Note that you'll get an unchecked cast warning, so make sure that
className
actually does represent an enum. You could check by calling theisEnum()
method on theClass
object, like this:Of course, you'll get a raw type warning on "
new EnumeratedThing(value1)
" anyway.只需在调用该方法之前强制转换您创建的类,
以便它符合方法签名:
现在该类被视为 Enum 的子类。
备注:
Just cast the class you create before you call the method,
so that it conforms to the method signature :
Now the class is seen as a subclass of Enum.
Remark :