[Simple-support] How can I serialize an unmodifiable list?
Brought to you by:
niallg
|
From: Lecomte, J-F. <JFL...@rh...> - 2012-11-29 01:15:16
|
I get a < NoSuchMethodException > when I try to serialize a list that is wrapped by Collections.unmodifiableList(...) or a list obtained by Arrays.asList(...). The same applies to UnmodifiableList from Google's Guava library.
Here is a snippet that exposes the problem:
public class Main
{
public static void main(final String[] args) throws Exception
{
final ArrayList<Integer> arrayList = new ArrayList<Integer>(Arrays.asList(1, 2, 3, 4));
testLoadSave(new ObjectToPersist(arrayList)); // Will be successful
testLoadSave(new ObjectToPersist(Collections.unmodifiableList(arrayList))); // Will throw a NoSuchMethodException
testLoadSave(new ObjectToPersist(Arrays.asList(5, 6, 7, 8)));
}
private static void testLoadSave(final ObjectToPersist objectToPersist) throws Exception
{
final Serializer serializer = new Persister();
final ByteArrayOutputStream out = new ByteArrayOutputStream();
serializer.write(objectToPersist, out);
final ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
final ObjectToPersist objectRead = serializer.read(ObjectToPersist.class, in);
System.out.println(objectRead);
}
public static class ObjectToPersist
{
@ElementList(name = "myList", entry = "element")
private final List<Integer> _myList;
public ObjectToPersist(
@ElementList(name = "myList", entry = "element") final List<Integer> myList)
{
_myList = myList;
}
public List<Integer> getMyList()
{
return _myList;
}
@Override
public String toString()
{
final StringBuilder builder = new StringBuilder();
builder.append("ObjectToPersist@");
builder.append(hashCode());
builder.append("[_myList=");
builder.append(_myList);
builder.append("]");
return builder.toString();
}
}
}
I don't really care about the exact type of the list stored in my object, but I would like to keep it unmodifiable. So far I fixed the problem by modifying "ObjectToPersist" class this way:
public ObjectToPersist(
@ElementList(name = "myList", entry = "element") final List<Integer> myList)
{
_myList = new ArrayList<Integer>(myList);
}
public List<Integer> getMyList()
{
return Collections.unmodifiableList(_myList);
}
But this implies creating a new ArrayList all the time. I would prefer something like this:
public ObjectToPersist(
@ElementList(name = "myList", entry = "element") final List<Integer> myList)
{
if (myList is already immutable)
_myList = myList;
else
_myList = new ArrayList<Integer>(myList);
}
public List<Integer> getMyList()
{
return _myList;
}
Using ImmutableList from Google's Guava library, I could do just this (ImmutableList.copyOf(...)), but it won't serialize... I was wondering if there was a way to support those immutable collections with SimpleXML...
Thanks!
JFL
|