Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No arg constructor and De serialization in Java

DeSerialization using the Serializable interface mechanism uses Reflection to deserialize the Object bytes to Object. But default no arg constructor is not called during this process and hence its not needed. But all the frameworks like Spring,Hibernate etc need no arg constructor even though they use Reflection. Isn't this contradictory or am I missing something?

like image 950
ghostrider Avatar asked Oct 20 '25 03:10

ghostrider


1 Answers

The builtin standard deserialization does not use standard reflection to create instances.

Standard reflection can not create instances without calling a constructor (not necessarily the no arg constructor). So any framework only using standard reflection will need to call a constructor for instance creation.

To create instances without calling a constructor you need some kind of jvm-vendor specific extension, like Unsafe. It is up to the framework developers to use these extensions, many decide against it. (XStream https://x-stream.github.io/faq.html is the only i am aware of that actually uses it)

like image 159
k5_ Avatar answered Oct 21 '25 18:10

k5_



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!