GWT Implementing Serializable - Private Default-Constructor - java

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 mechanism, wouldn't it be useful to make it private? This way, clients of the class don't accidentally call the default constructor, and the visible interface becomes smaller.
Or does it somehow affects the Serialization mechanism in any other way?

The GWT tutorial statement appears to apply to a specific requirement of GWT itself, or else it reiterates a common misunderstanding. The Java requirement is that the nearest non-serializable base class has an accessible default constructor. Not the serializable class itself.

the complete process of serialization involves also 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 can't have both private and public constructors with the same arguments (in GWT case the default - no args - one) stick with the public modifier.
cheers!

**WARNING THIS ANSWER IS NOT ABOUT HOW THE GWT COMPILER HANDLES ITS REQUIRED DEFAULT NO-ARG CONSTRUCTOR**
If you put it private, Serialization won't work.
From Javadoc :
"The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case. The error will be detected at runtime."
So yes, it will affect the Serialization process.
You could deprecate or comment this constructor indicating it is only used for Serialization purpose.
See here for details about serialization.

Related

Final class with private constructor, what is the design principle

I was recently going through one of the Netflix open source project
There I found use of both final class along with private constructor. I fully aware that
final is to avoid inheritance
private is to disallow instantiation
But m just curious to know why they are both used together. Although methods are static, so we can use them without instantiation but still eager to know design principle behind it.
With this code you will have this features
Not allow anyone subclass (extends) your class
Not allow instantiating your class
Making a variables or classes final increase the performance (not much, but it does and used as common practice in big projects will make a difference)
In this case I can't see a singleton pattern to get an instance, so, IMHO, you're looking to a helper/util class in the Netflix API, where the developer team used some standard practices to ensure users use their classes in the correct way:
StaticFinalClassExample.methodYouWantToCall();
Also, looking at the class you linked:
/**
* This class consists exclusively of static methods that help verify the compliance of OP1A-conformant....
*/
And:
//to prevent instantiation
private IMFConstraints()
{}
ADD ON:
If you want further info, take a look at Item 4 from Joshua Bloch's Effective Java (2nd Edition):
Item 4: Enforce noninstantiability with a private constructor
Occasionally you’ll want to write a class that is just a grouping of static methods and static fields. Such classes have acquired a bad reputation because some people abuse them to avoid thinking in terms of objects, but they do have valid uses.
They can be used to group related methods on primitive values or arrays, in the manner of java.lang.Math or java.util.Arrays.
They can also be used to group static methods, including factory methods (Item 1), for objects that implement a particular interface, in the manner of java.util.Collections.
Lastly, they can be used to group methods on a final class, instead of extending the class.
Such utility classes were not designed to be instantiated: an instance would be nonsensical. In the absence of explicit constructors, however, the compiler provides a public, parameterless default constructor. To a user, this constructor is indistinguishable from any other. It is not uncommon to see unintentionally instantiable classes in published APIs.
Attempting to enforce noninstantiability by making a class abstract does
not work. The class can be subclassed and the subclass instantiated. Furthermore, it misleads the user into thinking the class was designed for inheritance (Item 17).
There is, however, a simple idiom to ensure noninstantiability. A default constructor is generated only if a class contains no explicit constructors, so a class can be made noninstantiable by including a private constructor.
That class consists of static so called "utility" methods, and therefore you don't need an instance of it, and further, it's WRONG to try to get an instance of it. The class is final so that a client developer doesn't have the option of coming along and extending the class, because that would be against the intention of the original class.
There are basically 2 uses for private constructors: to tightly control instantiation in the case of a class that you want to restrict creation of (for example, if it requires a ton of resources). In this first case, you have to provide static factory methods that create an object for the client.
ie:
public static IMFConstraints getInstance()
The other case is if it's never valid to make an instance. In that case, you provide static methods, which are called on the class itself. ie:
public static void checkIMFCompliance(List<PartitionPack> partitionPacks)
You would call the above method like so:
// your cool client code here...
IMFConstraints.checkIMFCompliance(myPartitionPacks);
// more of your awesome code...
The class you linked is the latter case.

Why did it become a convention to create a non-arg constructor in a javabean?

I know
A JavaBean is just a standard
All properties private (use getters/setters)
A public no-argument constructor
Implements Serializable.
Source
We all know it is not required to provide a non argument constructor in a class, because if we have not specified any constructor in our class java compiler will create a non argument constructor. If so why programmers wanted to create a non argument constructor in a javabean as a convention.
You are confusing requirements on the JavaBean class with the requirements on its source code. No part of the JavaBeans specification deals with how your source code must look like, it is strictly about the resulting class.
So yes, each JavaBeans class must provide a nullary constructor, and how you achieve that with source code (or even with a bytecode generator) is completely up to you.
It is considered good practice by some to always include the non-arg constructor in your code, because that prevents the scenario where a later maintenance introduces another constructor, thereby discarding the implicit non-arg one, thereby breaking any external code that relies on it.
You don't have to create it explicitly. There's no rule saying you have to do that. Even for a JavaBean, it's fine to leave the compiler to create one for you (as long as you're not providing another one, in which case you'd need an explicit no-arg constructor too).
But there does need to be one, explicit or implicit, because the ORM needs to be able to create instances.
You'd want to create a no argument in these cases:
1) You want to do some logic in the no argument constructor, so can't use the default.
2) You have other constructors that take arguments, in that case no default no-arg constructor will be provided for you.
point 2 implies that having an explicit no arg constructor to start with allows you to add future constructors with arguments without worrying about losing the implicit no-arg constructor.
Without one many API internals like ORMs or IOC containers can't instantiate the object in order to proceed with setting the bean properties from the data source or other bean dependencies.
Many do approximately this:
Class<?> clazz = Class.forName("com.foo.BeanClass");
Constructor<?> constructor = clazz.getConstructor();
Object bean = constructor.newInstance();

Why can't I serialize an object without a no-arg constructor even though it implements Serializable?

I am trying to serialize a UUID with the Titan graph database and I believe I cannot because per the definition of Serializable, java.util.UUID fails to provide a no-arg constructor.
(See top of http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html for this)
Given that java.util.UUID claims to implement Serializable, what's going on here? Is this just a historical mistake that can't be removed for backward compatbility, or is there a specific technical reason for this weird (and to me, annoying) choice?
Update: Per the answer, UUID actually is Serializable and I misread the no-arg constructor rule which is subtle and does not actually require a no-arg constructor in the same class. The reason I couldn't serialize mine is that Titan (or its dependencies) adds a stricter no-arg declared constructor rule -- not core Java. I was confused as to who was imposing this rule, Java or Titan.
A Serializable class doesn't need a no-args constructor. Its nearest non-serializable base class does.
You've misread the specification.

JSF: Why do UIComponents need a no-args constructor?

Without one, component renders ok, however, using AJAX with re-renderable target within it fails (IllegalStateException).
I guess UIComponents need to accord to JavaBeans spec. But why do they need the non-args constructor? If I call UIComponent from a template, I understand that runtime needs to initialize a class with a non-args constructor and then set any properties, but in this case I was adding the component programmatically as:
MyComponent comp = new MyComponent("foo", "bar");
getChildren().add(comp);
So I wasn't calling a non-args constructor, and I don't know why JSF would either as AJAX should only re-render the component, not create a new instance from the component class?
You aren't calling it, but JSF might need to instantiate the component.
Take a look at the StateHolder interface (which is implemented by UIComponent). It explicitly states that a no-arg constructor is needed. And that's because this is a custom mechanism of saving and restoring state.
The thing is that JSF components are automatically serialized and de-serialized between requests. Default constructors (while in theory not absolutely necessary) make this a lot easier and are required by the Serializable API.
From the Serializable docs:
To allow subtypes of non-serializable
classes to be serialized, the subtype
may assume responsibility for saving
and restoring the state of the
supertype's public, protected, and (if
accessible) package fields. The
subtype may assume this responsibility
only if the class it extends has an
accessible no-arg constructor to
initialize the class's state. It is an
error to declare a class Serializable
if this is not the case. The error
will be detected at runtime.
The JSF framework must be able to instantiate new instances of UIComponent classes. There is no requirement for the UI tree to be held in RAM between requests and when this is the case, reflection is used to restore it.
UIComponent implementations do not implement Serializable and are not JavaBeans (per the strict definition). Implementing Serializable would not be useful because components can have a 1:n relationship with their state (e.g. they are the child of a repeating control).

Why do we need a default no argument constructor in Java?

Why do we need a default no argument constructor in many Java related APIs? Like as a general rule all java bean classes or entity classes (JPA etc) or JAX-WS implementation classes require a explicit no argument constructor.
If by default Java provides a no argument constructor then why most of these standards require a explicit constructor?
Java only provides a default no-argument constructor if no other constructors are defined. Thus, if you have other constructors you must explicitly define a no-arg constructor yourself.
These frameworks use the reflection API and look at method names to determine how to set properties. The arguments of a constructor can only be found by type, not by name, so there is no way for the framework to reliably match properties to constructor args. Therefore, they require a no-arg constructor to create the object, then can use the setter methods to initialise the data.
Some frameworks may support #ConstructorProperties as an alternative.
I believe frameworks that require public nullary constructors do so because they use reflection to instantiate types, e.g. through Class.newInstance().
As to why the default constructor may not work for this case, here's the relevant JLS section:
JLS 8.8.9 Default Constructor
If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided:
if the class is declared public, then the default constructor is implicitly given the access modifier public;
if the class is declared protected, then the default constructor is implicitly given the access modifier protected;
if the class is declared private, then the default constructor is implicitly given the access modifier private;
otherwise, the default constructor has the default access implied by no access modifier.
So in a public class, the default constructor would have the right visibility, but otherwise an explicitly public one must be provided.
A constructor is needed to initialise any non-default values and can contain side effects which are needed.
If you have a programing style which encourages a minimal constructor for data transfer objects this would seem unneccasary, but the libraries have chosen not to assume any programming style for the constructors.
You can write a library which doesn't assume a default constructor, but you have to make assumptions about what the constructor would do and wouldn't do. i.e. I have written such libraries but was able to also mandate what a constructor was allowed to do so that not calling it directly was safe.
Java only supplies a no-arg constructor if no other constructor is applied. In a number of Java APIs (e.g. JPA, Serialisation and many others that build objects from an external representation) an instance of the object is required before the data values of the object can be set, as the definition of how the values are applied are defined through instance members of the object (e.g. readExternal(ObjectInput)). If a class only has a constructor that takes some arguments then it may not be possible for the library to construct an instance unless a separate no-arg constructor is defined.
It is worth noting that this is a design choice by the implementer of the particular library, it is possible to build an API/Framework that can externalise and recreate objects that don't have a no-arg constructor (defining a separate factory class is one approach). The pattern of requiring a no-arg constructor turned up first in Java Serialisation (I think) and has been adopted as the de-facto standard approach on other libraries (e.g. JPA). The weakness of this approach is that it prevents the use of immutable objects.
Two reasons:
1) to avoid NullPointerException if an instance data field of a reference data type is uninitialized. Providing an explicit constructor would give you the chance to initialize such data fields, if they have not been initialized when declared
2) for users who would like to use no-arg constructors; these are not automatically provided if other constructors exist
Many of these frameworks derive from the earlier ideas of "POJO" and especially JavaBeans. The smallest useful Java Object would, by convention, have a no-arg constructor and every member accessible through methods like get/setProperty1 and is/setProperty1 for booleans. If Classes follow that convention of the interface, tools and frameworks using reflection can work 'out of the box'.
Default No-Argument constructor provides default values to the object like 0 or null, hence it is mandatory in java coding.

Categories