Jayesh
Jayesh

Reputation: 6111

How instance is created without calling constructor in java

I read on Deserializing java object and came to know that,

While deserializing java object, If instance implements the serializable interface, then an instance of the class is created without invoking it’s constructor.

By going through this link, I came to know Java uses sun.reflect.ReflectionFactory newConstructorForSerialization() method for creating new instance of Class without calling constructor.

Is it creates totally new constructor for deserialization process?

I want to know how object is created without calling its constructor. How this method actually works, can someone please explain in simple words.

Upvotes: 1

Views: 301

Answers (1)

Daniel Pryden
Daniel Pryden

Reputation: 60987

In Java bytecode the constructor is actually a method you call on an already created object. So if you're writing bytecode you can simply skip the second step.

In fact, there are a lot of control flow constructs that you can express in bytecode but that you can't write in Java source code.

Internally, Java serialization is built into the JVM so it can bypass any rules it likes.

This just underscores the difference between Java the programming language (where new always invokes the constructor) and Java the platform (where NEW is an opcode that pushes an unconstructed instance of the desired type onto the stack).

Upvotes: 1

Related Questions