Sunday, September 26, 2010

Re: GWT Custom Serialization

To deserialise an object, GWT calls the no-argument constructor (which you haven't specified, but is required) and then modifies the fields to match what is required. You can't modify fields if they're marked final, so GWT ignores final fields.

Don't forget that whatever approach is used it needs to (a) support class hierarchies and (b) be translatable to javascript and (c) work in the general case. That's why the gwt serialization rules are the way they are.

If you don't like the rules, you can always create a custom field serializer for each class and handle the serialization yourself.

Paul

On 25/09/10 17:31, Lucas Charron wrote:
I am having a slight problem with a framework I am making. Here is an example class: public class Example implements IsSerializable { private final int a;  private final int b;  public Example(int a,int b) { this.a=a; this.b=b; }  // getters ... }  A very simple class. However, there is no way to serialize it using GWT. Although the simple work-around is to remove the "final" attribute from the fields, that does not "jive" with, what I consider, solid programming. The "final" attribute means that no where, in any instance of the class or any instance of a descendant of this class, will the values of "a" and "b" be modified in any way (exception: using Java reflection). More than the optimization that many JVMs will do, there is also a type of safety - the programmer cannot accidentally put the reference on the left hand side of an assignment operator.  The GWT compiler will emit a warning that the final fields will not be serialized. Using the "_CustomFieldSerializer" is also impossible because the deserialize method takes an instance of the class you are deserializing as a parameter - instead it should have the return value as an instance of the class.  So, other than removing the final attribute, has anyone had any luck side-stepping this issue? Anyone know of any bug reports or enhancement requests for this (I have searched, but have come up empty).    

No comments:

Post a Comment