How new objects are instantiated when reading from object stream?

Hi,

How the serializable API instantiates new objects when reading from stream?

First it needs to create a new instance of a class and then fill its' fields with a serialized data. But not all serializable classes have empty constructor (as it have java beans) to make simple call of Class.newInstance(). Is there any way to create a virgin instance of any class?

Ant髇

[394 byte] By [throwablea] at [2007-11-26 13:40:06]
# 1
De-serialization does not call constructors. It has its own magic ways.
ejpa at 2007-7-7 22:35:53 > top of Java-index,Core,Core APIs...
# 2

I found the way, but it is not a solution:

Constructor serializableConstructor = sun.reflect.ReflectionFactory.getReflectionFactory().newConstructorForSerialization( Class instanceClass, Constructor superClassEmptyConstructor );

Object obj = serializableConstructor.newInstance();

This "magic" method creates an empty constructor for a serializable class from empty constructor of any superclass. The limitation is that a first non-serializable superclass must have an empty constructor.

As this magic method locates in a package sun.** I think this will not work with other JREs.

throwablea at 2007-7-7 22:35:53 > top of Java-index,Core,Core APIs...
# 3

> As this magic method locates in a package sun.** I

> think this will not work with other JREs.

And you shouldn't be using it. Serialization uses it, and serialization does work on other vendor's JREs, via whatever vendor-dependent magic is required, including the above on Sun JREs, and that's all you need to know.

ejpa at 2007-7-7 22:35:53 > top of Java-index,Core,Core APIs...
# 4

Hello!

You might be interested in the newly released project Objenesis, that does just that: allows the creation of objects bypassing constructors. Or, optionally, allows you to create objects in a serialization compatible way (i.e., calling the proper superclass constructor).

Check it out: http://objenesis.googlecode.com/svn/docs/index.html

Bubblea at 2007-7-7 22:35:53 > top of Java-index,Core,Core APIs...