views:

134

answers:

4

how does Serialization of objects works? How object got deserialized and a instance is created from serialized date without a call to any constructor?

A: 

Are you talking about Java? If so, serialization is an extralingual object creation mechanism. It's a backdoor that uses native code to create the object without calling any constructors. Therefore, when designing a class for serializability, you need to make sure that a class created through deserialization maintains the same invariants (key fields being initialized) as you would through the constructor path. A third way to create objects in Java is through cloning, and similar issues apply.

Cloning and serialization don't interact well with the use of final fields if you need to set the value of that field to something different than what is returned by clone or the deserialization process.

Josh Bloch's "Effective Java" has some chapters that explain these issues in more depth.

(this answer may apply to other languages too, but I've only used serialization in Java)

sk
A: 

for c# object serialization

Syed Tayyab Ali
A: 

Regarding .NET: this isn't a definitive or textbook answer, and I might be all-out wrong...

.NET Serialization needs to be seperated out into Binary vs. others (XML or an XML derivitave typically). Binary serialization is mostly a black-box to me, but it allows the object to be serialized and restored in their current state. XML serialization typically only serialized the public fields/properties of an object, unless overriden by adding a custom ISerializable implementation.

In the case of XML serialization I believe .NET uses Reflection to determine which fields and properties get converted to their equivalent Elements. Adding an [XMLSerializable] attribute will implement a default behavior which can be adjusted by applying other attributes at the field level (such as [XMLAttribute]).

The metadata (which Reflection depends on) stores all the object members as well as their attributes and addresses, which allows the serializer to determine how it should build the output.

STW
+3  A: 

I've kept this answer language agnostic since a language wasn't given.

When the object is serialized, all the require information to rebuild it is encoded in way which can be retrieved. This typically includes the type of the object, as well as the value of all the instance variables.

When the object is deserialized, an area in memory of the correct size is allocated and is populated using the serialized information such that the new object is identical to the serialized one.

The running program can then refer to this new object in memory without having to actually call the constructor.

There are lots of little details which this doesn't explain, but this is the general idea of serialization/deserialization.

Ben S
+1 Yea I think this is what his question is referring to.
TStamper