如果我在编译时不知道该类,那么如何获得枚举值? [英] How do I get the value of an Enum, if I don't know the class at compile time?
本文介绍了如果我在编译时不知道该类,那么如何获得枚举值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试执行以下操作:
I'm trying to do the following:
Class<?> cls = unknownClass;
if(cls.isEnum()){
@SuppressWarnings("unchecked")
Class<? extends Enum<?>> enumClass = (Class<? extends Enum<?>>) cls;
Object val = Enum.valueOf(enumClass, "NAME1");
}
但是我收到以下错误:
Bound mismatch: The generic method valueOf(Class<T>, String) of type Enum<E> is
not applicable for the arguments (Class<capture#5-of ? extends Enum<?>>, String).
The inferred type capture#5-of ? extends Enum<?> is not a valid substitute for
the bounded parameter <T extends Enum<T>>
有人可以告诉我我做错了什么?
Can someone tell me what I am doing wrong?
推荐答案
鉴于演员不会真正正在检查内容,我会使用完整的原始版本:
Given that the cast won't really be checking things, I'd go with the completely raw version:
if (cls.isEnum()){
@SuppressWarnings("unchecked")
Object val = Enum.valueOf(cls, "NAME1");
}
似乎有效。完整的例子:
That seems to work. Complete example:
public class Test
{
enum Foo
{
BAR, BAZ
}
public static void main(String[] args)
{
@SuppressWarnings("rawtypes")
Class cls = Foo.class;
if (cls.isEnum())
{
@SuppressWarnings("unchecked")
Object value = Enum.valueOf(cls, "BAR");
System.out.println(value);
}
}
}
这篇关于如果我在编译时不知道该类,那么如何获得枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文