Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is default no-args constructor mandatory for Gson?

People also ask

Does GSON need a default constructor?

Gson requires the class to have a default no-args constructor. If the no-args constructor is not provided, we can register an InstanceCreator with Gson, allowing us to deserialize instances of classes.

Why do we need no-arg constructor?

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.

Does Jackson require no-arg constructor?

Jackson won't use a constructor with arguments by default, you'd need to tell it to do so with the @JsonCreator annotation. By default it tries to use the no-args constructor which isn't present in your class.

What is a default no-arg constructor?

No-Arg Constructor - a constructor that does not accept any arguments. Parameterized constructor - a constructor that accepts arguments. Default Constructor - a constructor that is automatically created by the Java compiler if it is not explicitly defined.


As of Gson 2.3.1.

Regardless of what the Gson documentation says, if your class doesn't have an no-args constructor and you have not registered any InstanceCreater objects, then it will create an ObjectConstructor (which constructs your Object) with an UnsafeAllocator which uses Reflection to get the allocateInstance method of the class sun.misc.Unsafe to create your class' instance.

This Unsafe class goes around the lack of no-args constructor and has many other dangerous uses. allocateInstance states

Allocate an instance but do not run any constructor. Initializes the class if it has not yet been.

So it doesn't actually need a constructor and will go around your two argument constructor. See some examples here.

If you do have a no-args constructor, Gson will use an ObjectConstructor which uses that default Constructor by calling

yourClassType.getDeclaredConstructor(); // ie. empty, no-args

My 2 cents: Follow what Gson says and create your classes with a no-arg constructor or register an InstanceCreator. You might find yourself in a bad position using Unsafe.