What is the point to a serializable class? To my understanding its so that you can send objects across a network and know that on both ends that the object will be verified that it is the correct object. For example, if I have a server with a serializable class and want to send data to an app via object output stream, I can use the serializable class with the same UID on both ends to verify that the object is legitimate and not hacked? Please correct me if I'm wrong but that's how I am understanding the documentation on the serializable interface
- 3No, the point is not security. A man in the middle could easily replace your object with another one. The point is simply... to be able to transform object graphs to bytes and vice-versa, in a very easy way.JB Nizet– JB Nizet2016-06-08 20:23:09 +00:00Commented Jun 8, 2016 at 20:23
- A serializable class can be written and read from a file automatically by java (as long as it has access to the class). This allows things like a JMS Queue to write classes to a file when the message containing the class is on the queue.DwB– DwB2016-06-08 20:51:34 +00:00Commented Jun 8, 2016 at 20:51
2 Answers
Security and Serialization both are different.
Java serialization is to convert the objects to bytes. Period.
The optional UID field is to assure the serialized and deserialized object (structure) versions match.
Serialization is useful to convert an object into a file and reload it back into an object later in future, and of course you can send that file (stream) over the network also.
6 Comments
List<User> over an ObjectOutputStream, and how it would look on the client side when its sent from server to client @K139You're correct, but you can think of it more broadly.
You can convert a serializable class to bytes
You can add an object of this type to a serializable collection and it will be properly serialized (e.g. you can make a list of them and serialize the list if the list is serializable)
By the way, the serialVersionUID is optional. It will generate one on its own, though it will be a bit more fragile - if you change, for example, a method signature, the jvm will translate this to an altered signature and believe that the class is now incompatible with previous serialized versions, even if you haven't changed data fields. If you create your own you're essentially overriding this mechanism.