Jack Edmonds
Jack Edmonds

Reputation: 33221

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

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.

Upvotes: 22

Views: 28151

Answers (4)

Roman
Roman

Reputation: 66226

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

Upvotes: 10

jqno
jqno

Reputation: 15530

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

Deserializing an object will also bypass the constructor.

It isn't possible to do this using reflection.

Upvotes: 33

Richard Fearn
Richard Fearn

Reputation: 25511

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.

Upvotes: 7

meriton
meriton

Reputation: 70584

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.

Upvotes: 7

Related Questions