Thursday, January 23, 2014

serialization of classes that require non-default constructors and extending these classes

Suppose, there's a 3rd party class:

    public class A {
        private int v;
        public A(int v) {
            this.v = v;
        }
        public int v() {
            return v;
        }
    }

If you want it to deserialize on client, you usually write a CustomFieldSerializer that calls the constructor in instantiate():

    public class A_CustomFieldSerializer extends CustomFieldSerializer<A> {
        public static void deserialize(SerializationStreamReader streamReader,
                A instance) throws SerializationException {
        }
        public static A instantiate(SerializationStreamReader streamReader)
                throws SerializationException {
            return new A(streamReader.readInt());
        }
        public static void serialize(SerializationStreamWriter streamWriter,
                A instance) throws SerializationException {
            streamWriter.writeInt(instance.v());
        }
        @Override
        public void deserializeInstance(SerializationStreamReader streamReader,
                A instance) throws SerializationException {
            deserialize(streamReader, instance);
        }
        @Override
        public boolean hasCustomInstantiateInstance() {
            return true;
        }
        @Override
        public A instantiateInstance(SerializationStreamReader streamReader)
                throws SerializationException {
            return instantiate(streamReader);
        }
        @Override
        public void serializeInstance(SerializationStreamWriter streamWriter,
                A instance) throws SerializationException {
            serialize(streamWriter, instance);
        }
    }

If someone tries to extends this class, deserialization corrupts the stream, because readInt() is not called:

    public class B extends A {
        public B() {
            super(0);
        }
    }

--
You received this message because you are subscribed to the Google Groups "Google Web Toolkit" group.
To unsubscribe from this group and stop receiving emails from it, send an email to google-web-toolkit+unsubscribe@googlegroups.com.
To post to this group, send email to google-web-toolkit@googlegroups.com.
Visit this group at http://groups.google.com/group/google-web-toolkit.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment