Serialization problem with Enums at Android

 ̄綄美尐妖づ 提交于 2019-12-01 10:53:25

问题


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".

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.

Can you confirm/refute this is the problem with Android? Can you suggest any other serialization API that could be used in this situation?


回答1:


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);
    }
}

Use

XStream xml = new XStream();
xml.registerConverter(new SingleValueEnumConverter([ENUM].class));



回答2:


You can just register EnumConverter() from xstream package.

xml.registerConverter(new EnumConverter());



回答3:


Pintac's answer still contains a bug. It still does not use the name() method, according to Java spec. After a thread at XStream mailing list, the bug was fixed in any release greater 1.3.1. Please see the thread "Enum on Android" at the mailing list.

The fixed version:

   class FixedEnumSingleValueConverter extends EnumSingleValueConverter {
      FixedEnumSingleValueConverter(Class eType) {
        super(eType);
      }

      public toString(Object obj) {
        return Enum.class.cast(obj).name();
      }
    }

    xstream.registerConverter(new FixedEnumSingleValueConverter(Sample.class));

It was from the developer of XStream.



来源:https://stackoverflow.com/questions/3533894/serialization-problem-with-enums-at-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!