Why does Hibernate require no argument constructor?

unj2 picture unj2 · May 29, 2010 · Viewed 86.2k times · Source

The no-argument constructor is a requirement (tools like Hibernate use reflection on this constructor to instantiate objects).

I got this hand-wavy answer but could somebody explain further? Thanks

Answer

mdma picture mdma · Jun 4, 2010

Hibernate, and code in general that creates objects via reflection use Class<T>.newInstance() to create a new instance of your classes. This method requires a public no-arg constructor to be able to instantiate the object. For most use cases, providing a no-arg constructor is not a problem.

There are hacks based on serialization that can work around not having a no-arg constructor, since serialization uses jvm magic to create objects without invoking the constructor. But this is not available across all VMs. For example, XStream can create instances of objects that don't have a public no-arg constructor, but only by running in a so-called "enhanced" mode which is available only on certain VMs. (See the link for details.) Hibernate's designers surely chose to maintain compatibility with all VMs and so avoids such tricks, and uses the officially supported reflection method Class<T>.newInstance() requiring a no-arg constructor.