java Java通过反射创建一个枚举实例

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5108281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:29:08  来源:igfitidea点击:

Java create an instance of enum via reflection

javareflectionenums

提问by michelemarcon

I want to get an instance to an enum type, so that:

我想获得一个枚举类型的实例,以便:

String enumString="abc";
MyClass.MyEnum enumType=Class.forName("com.MyClass.MyEnum."+enumString);

This gives me an inconvertible types.

这给了我一个不可转换的类型。

回答by ataylor

Enum.valueOfwill do it, but it is pretty picky about it's type. Make sure you cast the Classto Class<? extends Enum>. Example:

Enum.valueOf会做到这一点,但它对它的类型非常挑剔。确保你投射ClassClass<? extends Enum>. 例子:

enum Foo {
    BLAT,
    BLARG
};

System.out.println(Enum.valueOf((Class<? extends Enum>)Class.forName("Foo"), "BLARG"));

回答by Yishai

You are looking for MyClass.MyEnum.valueOf(enumString). No need to fully qualify the class in the string.

您正在寻找MyClass.MyEnum.valueOf(enumString). 无需完全限定字符串中的类。