我在XML中定义了类似的内容:
<Property>
<value>APPLE</value>
<enum>com.mycompany.MyEnum</enum>
</Property>
我尝试在代码中实例化枚举。这是我到目前为止所拥有的
Class<?> clazz = Class.forName(pProperty.getEnum());
if (!clazz.isEnum())
throw new IllegalArgumentException(MessageFormat.format("Class %s is not an enumeration.", pProperty.getEnum()));
之后,我尝试调用valueOf(java.lang.String),但是我得到了NoSuchMethodException
MyEnum的定义如下:
package com.mycompany;
public enum MyEnum
{
APPLE, PEER, LEMON
}
有可能吗?
由于
答案 0 :(得分:1)
不确定这是不是你的意思,但是如果你想从APPLE
中描述的enum中获得<enum>com.mycompany.MyEnum</enum>
枚举常量,你可以尝试这样的事情
@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());
}
答案 1 :(得分:0)
这对我有用:
clazz.getMethod("valueOf", String.class).invoke(null, "APPLE")
答案 2 :(得分:0)
以下方法从属性文件数组中读取以获取枚举值。您应该能够调整它们以从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;
}