What does the term “Serializable” mean? [duplicate]

半城伤御伤魂 提交于 2019-12-02 03:46:14

问题


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 a private 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() and writeReplace().

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!