Serialization issue with Enums on Android

I am using XStream to serialize some objects in XML and am facing a problem with Enums. The exception that I get when I try to serialize an object is: "ObjectAccessException: invalid final field java.lang.Enum.name".

Apparently, this is a problem with the implementation of the reflection API in android: it does not handle the final fields correctly. This problem really existed in previous implementations of the official Sun (Oracle) JDK.

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

+1
source share
3 answers

The only way I could find to get around this was to create an AbstractSingleValueConverter for the enumerations, 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);
    }
}

Using

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

You can simply register EnumConverter () from the xstream package.

xml.registerConverter(new EnumConverter());
+2
source

Pintac - . - name(), Java. XStream ​​ 1.3.1. . "Enum on Android" .

:

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

XStream.

0

Source: https://habr.com/ru/post/1761986/


All Articles