Java serialization issues when using guava Lists.transform

I had to serialize a complex object, but one of its components was a non-serializable (third-party graph object), so I created a special serializable version of this Graph class and used the Guava List transform to convert the non-serializable object to custom objects. The writeObject sequence for serialization has not yet completed. I will be interested to know why? My guess is that List.transform is doing its Leni operation (by holding a hidden link to the original object.)

Also is there a workaround for this problem?

+6
source share
3 answers

List.transform () performs lazily as you suspected. You can do one of

Lists.newArrayList(Lists.transform(...)) 

or, if you want an immutable version,

 ImmutableList.copyOf(Lists.transform(...)) 

and then serialize the resulting list.

+11
source

List.transform () returns a transformed representation of the original list. From the list of Lists.transform () javadoc :

The returned list always implements Serializable, but serializes only if the fromList and function are serializable.

When serializing a converted view, you actually serialize the source list as well as the function. In your case, this fails because your source list is not serializable (since it contains non-serializable graph elements). But it can also fail, because the function does not implement serializable.

By the way, there is a little trick for creating serializable functions without verbosity. Instead of this:

  private static final class MyFunction extends Function<String, String> implements Serializable { private static final MyFunction INSTANCE = new MyFunction(); @Override public String apply(String input) { return "[" + input + "]"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } 

You can use a singleton enumeration template that is much less verbose, and you get serialized for free (since enums are serializable). It also ensures that your function is single:

  // enum singleton pattern private enum MyFunction implements Function<String, String> { INSTANCE; @Override public String apply(String input) { return "[" + input + "]"; } } 
+6
source

If you try to serialize the list returned from the List # conversion, the list of interfaces itself will not be Serializable.

+1
source

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


All Articles