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

查看:35
本文介绍了为什么 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.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 魔法在不调用构造函数的情况下创建对象.但这并非适用于所有 VM.例如,XStream 可以创建没有公共无参数构造函数的对象实例,但只能通过在所谓的增强"模式下运行,该模式仅在某些 VM 上可用.(详情请参见链接.)Hibernate 的设计者肯定选择保持与所有 VM 的兼容性,因此避免了此类技巧,并使用官方支持的反射方法 Class.newInstance() 不需要 -arg 构造函数.

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天全站免登陆