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

RRR_J picture RRR_J · Jun 20, 2010 · Viewed 20.3k times · Source

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?

Answer

OrangeDog picture OrangeDog · Dec 20, 2010

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.