为什么Hibernate不需要参数构造函数? [英] Why does Hibernate require no argument constructor?

查看:268
本文介绍了为什么Hibernate不需要参数构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


无参数构造函数是一个
需求(像Hibernate这样的工具在这个构造函数中使用
反射对
实例化对象)。

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

推荐答案

Hibernate和一般通过反射创建对象的代码使用 Class< T> .newInstance() 创建你的类的新实例。这个方法需要一个公共的无参数构造函数来实例化对象。对于大多数用例,提供一个无参数构造函数不是问题。

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.

有些基于序列化的黑客可以解决没有无参数构造函数的问题,因为序列化使用jvm魔术来创建对象而无需调用构造函数。但是这在所有虚拟机中都不可用。例如, XStream 可以创建没有公共无参数构造函数的对象的实例,但只能通过仅在特定VM上可用的所谓增强模式运行。 Hibernate的设计人员当然选择保持与所有虚拟机的兼容性,避免这种技巧,并使用官方支持的反射方法 Class< T> .newInstance()需要一个无参数构造函数。

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.

这篇关于为什么Hibernate不需要参数构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆