是否可以在不调用构造函数的情况下在 Java 中创建对象的实例?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3488097/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:02:28  来源:igfitidea点击:

Is it possible to create an instance of an object in Java without calling the constructor?

java

提问by Hyman Edmonds

I'm trying to fix a bug in one of my programs which I think might be due to Hibernate figuring out how to instantiate an instance of an object without calling its default (or any other) constructor.

我正在尝试修复我的一个程序中的一个错误,我认为这可能是由于 Hibernate 弄清楚如何在不调用其默认(或任何其他)构造函数的情况下实例化对象的实例。

回答by jqno

Actually, yes, it is possible to bypass the constructor when you instantiate an object, if you use objenesisto instantiate the object for you. It does bytecode manipulations to achieve this.

实际上,是的,如果您使用objenesis为您实例化对象,则可以在实例化对象时绕过构造函数。它执行字节码操作来实现这一点。

Deserializing an object will also bypass the constructor.

反序列化对象也将绕过构造函数。

It isn't possible to do this using reflection.

使用反射无法做到这一点。

回答by Roman

Just to complete the picture: using method cloneto create a new object bypasses constructors as well.

只是为了完成图片:使用方法clone创建新对象也绕过构造函数。

回答by meriton

Yes, deserializing an object does not invoke its constructor.

是的,反序列化一个对象不会调用它的构造函数。

That said, I don't see why hibernate would serialize an object, unless perhaps in the second level cache.

也就是说,我不明白为什么 hibernate 会序列化一个对象,除非可能在二级缓存中。

回答by Richard Fearn

Deserialization involves creating objects without invoking a constructor.

反序列化涉及在不调用构造函数的情况下创建对象。

It's possible (at least with the Sun/Oracle JDK) to do this programmatically. This was covered in "Creating Objects Without Calling Constructors", an edition of The Java Specialists' Newsletter.It involves using classes from the sun.*packages so isn't portable.

可以(至少使用 Sun/Oracle JDK)以编程方式执行此操作。这浑身上下“创建对象,而不调用构造函数”,一个版本的Java的专家通讯。它涉及使用sun.*包中的类,因此不可移植。