问题
Not quite sure by the definitions I have read what serializable actually does...
import java.io.Serializable;
import java.text.StringCharacterIterator;
import java.util.*;
import java.io.*;
public final class SavingsAccount implements Serializable {
回答1:
When you use implements Serializable
you can convert an object in bytes, so the object can be send across the network, can be saved in a directory, and rebuild in the other side of the network, etc.
回答2:
Serialization allows you to turn your class (if it implements Serializable
) into a data stream and be transfered over a network, or saved onto disk.
This should give you some good examples and a good description.
回答3:
Serialization in general means that at the language level there exists a certain level at which entities of the language can be "persisted" in some form, and read back from that persisted form.
That persisted form is more often than not a stream of bytes, which is saved into a file; and you read back from that file in order to recreate the entity at runtime.
In Java, the basic entity which can be persisted/serialized is an Object
; and in order for it to be a candidate for serialization, it must implement the Serializable
interface.
Now, this particular interface is a trap; it has many, many conditons to it being implemented correctly. Among others:
- ideally, you want all of your
Serializable
instances to define aprivate static final long serialVersionUUID
, and yes, here, the name of the variable matters, it cannot be anything else; - you may have instance variables in your object which you do not want to serialize: those should be marked as
transient
; - you should ensure that all instance variables, apart from the
transient
ones, are themselves serializable; if not you must implement, at the very least, the{read,write}Object()
methods, or to an even finer grained resolution,readResolve()
andwriteReplace()
.
In other words: good luck!
Note: maybe you also want to have a look at Externalizable
.
来源:https://stackoverflow.com/questions/33546411/what-does-the-term-serializable-mean