序列化问题在枚举的Android [英] Serialization problem with Enums at Android
问题描述
我用XStream序列一些对象到XML,以及现在面临与枚举的问题。我得到当我尝试序列化对象的异常:ObjectAccessException:无效的最后一个字段java.lang.Enum.name。
I'm using XStream to serialize some objects to XML, and am facing a problem with Enums. The exception I get when I try to serialize the object: "ObjectAccessException: invalid final field java.lang.Enum.name".
显然,这是在Android的反射API实现了一个问题:它没有正确处理最后的领域。这个问题确实存在于过去官方的太阳(Oracle)的JDK的实现。
Apparently, this is a problem with the reflection API implementation in android: It doesn't treat final fields correctly. This problem actually existed in past implementations of the official Sun (Oracle) JDK.
你能确定/反驳,这是与Android的问题?你可以提出任何其他序列化的API,可以在这个情况下使用?
Can you confirm/refute this is the problem with Android? Can you suggest any other serialization API that could be used in this situation?
推荐答案
我能找到解决这个问题是创建一个AbstractSingleValueConverter的枚举,然后使用XStream注册的唯一方法。
The only way i could find to get around this is to create a AbstractSingleValueConverter for enums and then register it with xstream.
public class SingleValueEnumConverter extends AbstractSingleValueConverter
{
private final Class enumType;
public SingleValueEnumConverter(Class type)
{
this.enumType = type;
}
public boolean canConvert(Class c)
{
return c.equals(enumType);
}
public Object fromString(String value)
{
return Enum.valueOf(enumType, value);
}
}
使用
XStream xml = new XStream();
xml.registerConverter(new SingleValueEnumConverter([ENUM].class));
这篇关于序列化问题在枚举的Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!