Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 916
Jack Edmonds Avatar asked Aug 15 '10 15:08

Jack Edmonds


People also ask

Can I create an object without calling the constructor?

Abstract: De-Serialization creates objects without calling constructors. We can use the same mechanism to create objects at will, without ever calling their constructors. Welcome to the 175th issue of The Java(tm) Specialists' Newsletter.

Can you make instances of a class without constructor Java?

With serialization, you create a new object by deserializing the whole object state from an input stream. No constructor is invoked in this case. With JNI, there is the AllocObject function, which allocates the space for a new object, also without calling a constructor.

Can you instantiate a class without constructor?

You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors.

Do we need a constructor before we can create an object instance?

A constructor is a special method of a class that initializes new objects or instances of the class. Without a constructor, you can't create instances of the class.


2 Answers

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.

like image 181
jqno Avatar answered Sep 29 '22 06:09

jqno


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

like image 32
Roman Avatar answered Sep 29 '22 08:09

Roman