From What's this "serialization" thing all about?:
It lets you take an object or group of objects, put them on a disk or send them through a wire or wireless transport mechanism, then later, perhaps on another computer, reverse the process: resurrect the original object(s). The basic mechanisms are to flatten object(s) into a one-dimensional stream of bits, and to turn that stream of bits back into the original object(s).
Like the Transporter on Star Trek, it's all about taking something complicated and turning it into a flat sequence of 1s and 0s, then taking that sequence of 1s and 0s (possibly at another place, possibly at another time) and reconstructing the original complicated "something."
So, implement the Serializable
interface when you need to store a copy of the object, send them to another process which runs on the same system or over the network.
Because you want to store or send an object.
It makes storing and sending objects easy. It has nothing to do with security.
The answer to this question is, perhaps surprisingly, never, or more realistically, only when you are forced to for interoperability with legacy code. This is the recommendation in Effective Java, 3rd Edition by Joshua Bloch:
There is no reason to use Java serialization in any new system you write
Oracle's chief architect, Mark Reinhold, is on record as saying removing the current Java serialization mechanism is a long-term goal.
Java provides as part of the language a serialization scheme you can opt in to, by using the Serializable
interface. This scheme however has several intractable flaws and should be treated as a failed experiment by the Java language designers.
Instead, use a serialization scheme that you can explicitly control. Such as Protocol Buffers, JSON, XML, or your own custom scheme.
Implement the Serializable
interface when you want to be able to convert an instance of a class into a series of bytes or when you think that a Serializable
object might reference an instance of your class.
Serializable
classes are useful when you want to persist instances of them or send them over a wire.
Instances of Serializable
classes can be easily transmitted. Serialization does have some security consequences, however. Read Joshua Bloch's Effective Java.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With