【发布时间】:2009-07-30 20:34:35
【问题描述】:
一位同事今天遇到了一个有趣的问题,虽然我认为实际的、宏观的答案是“我们遇到这个问题的事实意味着我们做错了什么”,但我想我会无论如何都要问这个。
鉴于以下情况:
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<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>>
所以,我的问题是:是否有可能,仅给定枚举类型名称的 String 表示形式以及其中一个值的 .name(),获取对相应枚举类型对象的引用作为 Enum ?
【问题讨论】:
标签: java serialization enums