Reputation: 11
I don't currently understand why I would choose to serialize an object instead of just doing a file output and then having a function read that file. What do I gain from serializing an object?
Upvotes: 1
Views: 61
Reputation: 2185
When you serialize
an object
, you are copying the actual byte
data in memory into a stream
. When you de-serialize
that stream back into an object
you get the identical object back including its internal object ID, which you would not get if you had written the properties of the object to a file, and then read it back in and interpreted it.
This means, if you serialize
a collection of objects
that reference
each other, when you de-serialize
them, they will still maintain their references
to each other. This is good also for debugging a program. If an exception occurs you can create a memory dump on the users computer, and if they send it to you, then you can see directly what was in memory and the problems that may have been caused.
It is also easier to serialize
a complex object
with many properties to a stream
than it is to build some string
of representative data, which you will have to be read back, parse and construct a new object
with it.
Really what you gain, is that it is easier/quicker and better for debugging.
Upvotes: 0
Reputation: 4496
Serialization makes it easy to store the state of objects,
and objects inside them (If they are Serializable
and not marked as transient
).
The benefits in your case :
Imagine you have a lot of different classes. Maybe coding a custom File-to-class
parser is harder than readObject()
Upvotes: 1
Reputation: 180787
You gain an industry-standard way of reading and writing an object's data, using a W3C approved data exchange format that has almost universal support for readers and writers in almost every programming language.
Upvotes: 2