我试图通过解析 xml 文档来查找值,以编程方式设置 Field
的值。
我的结构有点像这样:
value = parseXml();
field.set(myObject, value);
private Object parseXml()
{
String value = getValueFromXmlNode();
if (type.isInstance(Enum.class))
{
return Enum.valueOf(((Class<Enum>) type), value);
}
else
{
return value;
}
}
这对于大多数情况都适用。但是,如果该字段需要 Enum
,则此方法不再有效。因为我将方法的返回类型设置为 Object
,所以枚举被转换为 String。然后 field.set()
调用失败。
让方法返回可能是Enum
的泛型类型的正确方法是什么?
对于原始类型,有自动装箱和取消装箱的对象包装器,Enum
是否有类似的东西?
最佳答案
Because I set the return type of my method as Object, the enum gets casted to a String instead.
不,没有。
With primitive types there are Object wrappers that autobox and unbox, does Enum have something like that?
枚举值是对象。您已经可以将枚举值放入对象变量中。
我相信问题出在这一行:
if (type.isInstance(Enum.class))
应该是:
if (type.isEnum())
isInstance
调用不会执行您想要的操作,因为它询问 Class 对象是否 Enum.class
是 instanceof
type
类。
然后,因为 if
检查不起作用,它总是选择返回 String value
的第二个分支按原样,这就是为什么枚举本身似乎被转换为字符串。
关于java - 返回枚举作为对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22006190/