GWT Serializable Implementation - Private Default Constructor

The GWT tutorial says:

As of GWT 1.5, it must have a default (zero argument) constructor (with any access modifier) or no constructor at all. 

So, when the default constructor is only used by the Serialization engine, would it not be useful to make it private ? Thus, class clients do not accidentally call the default constructor, and the visible interface becomes smaller.

Or does this somehow affect the Serialization mechanism?

+4
source share
3 answers

** WARNING THIS ANSWER DOES NOT UNDERSTAND HOW THE GWT COMPILLER REVERSES ITS NECESSARY BUILT-IN NO-ARG CONSTRUCTOR **
If you put it in private, serialization will not work.

From Javadoc: "A subtype can take this responsibility only if the class that it extends has an available no-arg constructor to initialize the state of the class . This is a Serializable class declaration error if it is not. An error will be detected at runtime."

So yes, this will affect the Serialization process.

You can refuse or comment on this constructor, indicating that it is used only for serialization purposes.

See more about serialization here .

-2
source

The GWT textbook manual seems to be applicable to the specific requirement of the GWT itself, or it repeats a general misunderstanding. The Java requirement is that the closest non-serializable base class has an available default constructor. Not a serializable class itself.

+6
source

the entire serialization process also includes deserialization, in which the java object will be reconstructed.

Therefore, adding a private constructor to a serializable class will not work on the way back (deserialization), and since you cannot have both private and public constructors with the same arguments (in the case of GWT, the default value is no arguments) stick to the public modifier.

Hooray!

0
source

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


All Articles