[英]Create Java enum by type and value as strings
I have defined in an XML something like : 我已经在XML中定义了类似以下内容:
<Property>
<value>APPLE</value>
<enum>com.mycompany.MyEnum</enum>
</Property>
I try to instantiate that enum in code. 我尝试在代码中实例化该枚举。 here is what I have so far
这是我到目前为止所拥有的
Class<?> clazz = Class.forName(pProperty.getEnum());
if (!clazz.isEnum())
throw new IllegalArgumentException(MessageFormat.format("Class %s is not an enumeration.", pProperty.getEnum()));
After that, I try to call valueOf(java.lang.String), but I got a NoSuchMethodException 在那之后,我尝试调用valueOf(java.lang.String),但是我收到了NoSuchMethodException
MyEnum is defined like this : MyEnum的定义如下:
package com.mycompany;
public enum MyEnum
{
APPLE, PEER, LEMON
}
Is it possible to do that ? 有可能这样做吗?
Thanks 谢谢
Not sure if that is what you mean but if you want to get enum constant like APPLE
from enum described in <enum>com.mycompany.MyEnum</enum>
you can try something like this 不确定这是否是您的意思,但是如果您想从
<enum>com.mycompany.MyEnum</enum>
描述的<enum>com.mycompany.MyEnum</enum>
获取像APPLE
这样的枚举常量,您可以尝试这样的操作
@SuppressWarnings("rawtypes")
Class clazz = Class.forName("com.mycompany.MyEnum");
if (clazz.isEnum()) {
@SuppressWarnings("unchecked")
Enum<?> o = Enum.valueOf(clazz, "PEER");
System.out.println(o.name());
System.out.println(o.ordinal());
}
这为我工作:
clazz.getMethod("valueOf", String.class).invoke(null, "APPLE")
The following methods read from an array of properties files to get an enum's value. 以下方法从属性文件数组读取以获取枚举的值。 You should be able to adapt them to read from an XML file:
您应该能够使它们适应从XML文件读取的内容:
public static <T extends Enum<?>> T getEnumProperty(String key, Class<T> type, T defVal, Properties... properties)
{
String val = getProperty(key, properties);
if(val == null)
{
System.out.println("Using default value for: " + key);
return defVal;
}
T[] enums = type.getEnumConstants();
for(T e : enums)
{
if(e.name().equals(val))
return e;
}
System.out.println("Illegal enum value '" + val + "' for " + key);
return defVal;
}
private static String getProperty(String key, Properties... properties)
{
for(Properties p : properties)
{
String val = p.getProperty(key);
if(val != null)
{
val = val.trim();
}
return val;
}
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.