0

I was wondering, if I can cheat serialization by wrapping them in local nested classes, something like this:

I have a service which I need to pass around, but it internally has some very complex data.

 interface ComplexService {
       IncredibleComplexObject getData();
   }

So I thinking about wrapping it in another class that is serializeable via decorator pattern.

public final class Utils {

   public static Serializable wrap(final ComplexService service) {
       class WrapperService implements ComplexService, Serializeable {
           @Override
           public IncredibleComplexData getData() {
                return service.getData();
           }
       };
       return new WrapperService();
   }
}

I actually don't believe that I can cheat serialization like that, because it would be a little bit too much magic if Java could actually recreate my class that is dependent on my final ComplexService-parameter. But I am wondering, why exactly this fails and what exception would be thrown, where and why.


(just for clarification why I would want to do this: I am on android and I need to pass this service to a Fragment, which naturally can only save serializeable objects).

Flo
  • 1,469
  • 1
  • 18
  • 27
  • Can't ComplexService be serializable too (i.e. extend Serializable)? – jamp Oct 15 '14 at 15:21
  • `ComplexService` itself can't be serializable, because its actual implementation caches the `IncredibleComplexObject` in a field, thus would not be serializable. – Flo Oct 16 '14 at 15:30
  • and can't IncredibleComplexObject be serializable? :P Anyway, after you wrap it in WrapperService, how will you be able to call getData() from outside? It's an inner-method-class... – jamp Oct 17 '14 at 14:35

1 Answers1

1

Yes, you can wrap your non-serializable object in a serializable wrapper. No, it won't magically make the wrapped object serializable. You'll get a NotSerializableException if you attempt to serialize the wrapper class (without making that field transient).

Community
  • 1
  • 1
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • In my example my wrapper class actually does not have any fields, so I would expect that serialization still works, but deserialization would likely cause an exception, am I wrong? – Flo Oct 16 '14 at 00:20
  • Funny thing, i just tried it out and you are right - I don't get an exception when deserializing - I am already getting an exception when serializing. Why we should not serialize inner classes anyway, is described here: http://stackoverflow.com/a/17805016/1406325 – Flo Nov 07 '14 at 13:40