Serializing Immutable Objects in GWT

Serializing Immutable Objects in GWT

Immutable objects are an easy yet powerful way to leverage some of the advantages of functional programming languages when writing plain old java. Such immutable objects declare all their attributes as final and are therewith protected from unforeseen state changes and side-effects. However, unfortunately the GWT RPC mechanism has problems in dealing with immutable objects. In particular, GWT RPC does not consider final attributes in serialization and deserialization of objects.

What GWT does support:

What GWT does not support:

Final fields will be treated as transient fields (and therewith omitted during serialization). GWT compiler will report for instance "[WARN] Field 'public final java.lang.String name' will not be serialized because it is final".

GWT compiler will report: "[Type] is not default instantiable (it must have a zero-argument constructor or no constructors at all) and has no custom serializer" or "[Type] has no available instantiable subtypes"

What can be done:

-0- Try Direct Eval RPC ?

There is a newer version of the RPC mechanism called Direct-Eval RPC (or short deRPC). This mechanism (besides bringing improvements in the client-side deserialization performance) is supposed to allow serializing final fields. However, using GWT 2.1.0 and the gwt-maven-plugin version 2.1.1-SNAPSHOT, final fields would still be ignored during serialization and deserialization. Moreover, the mechanism would still require a no argument constructor. Most sensible immutable objects require a constructor with arguments (to initialize the final fields).

-1- Add 'dummy' constructors to your classes:

Take all possible precautions that this constructor is not used in any other place in your code: (1) Declare as private, (2) Declare as Deprecated (which it will hopefully be if GWT serialization mechanism evolves), (3) add warning Java doc.

/* #gwtdummyconstrstart */

/**

* Non-argument constructor required for GWT RPC serialization.

* DO NOT CALL this constructor manually.

*/

@SuppressWarnings("unused")

@Deprecated

private Person() {

}

/* #gwdummytconstrend */

-2- Remove the final modifier from all fields in classes, which need to be serialized

Here again, it might be a good idea to somehow make the omitted final modifiers easily replaceable (in hope that future versions of gwt will support immutable objects).

/* #gwtnofinal */ private String name;

Hints

deRPC is supposed to support the serialization of classes with non-final fields. However, the compile still issues warnings for all these fields (for good reasons as the final fields were still ignored in my case). It is possible to suppress these warnings by adding the following element to the Gwt module definition (gwt.xml) (see Issue 2862):

Resources

Direct Evalable RPC GWT Wiki

GWT Docs Communicate with a Server

GWT Docs Direct-Eval RPC (deRPC)