Java 什么是对象序列化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/447898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is object serialization?
提问by Warrior
What is meant by "object serialization"? Can you please explain it with some examples?
“对象序列化”是什么意思?你能用一些例子解释一下吗?
采纳答案by TarkaDaal
Serialization is the conversion of an object to a series of bytes, so that the object can be easily saved to persistent storage or streamed across a communication link. The byte stream can then be deserialized - converted into a replica of the original object.
序列化是将对象转换为一系列字节,以便对象可以轻松保存到持久存储或通过通信链接流式传输。然后可以反序列化字节流 - 转换为原始对象的副本。
回答by Kent Boogaart
Serialization is taking a "live" object in memory and converting it to a format that can be stored somewhere (eg. in memory, on disk) and later "deserialized" back into a live object.
序列化是将内存中的“活动”对象转换为可以存储在某处(例如,在内存中、磁盘上)的格式,然后“反序列化”回活动对象。
回答by Cheese Daneish
Serialization is the process of converting an object's state to bits so that it can be stored on a hard drive. When you deserialize the same object, it will retain its state later. It lets you recreate objects without having to save the objects' properties by hand.
序列化是将对象的状态转换为位以便将其存储在硬盘驱动器上的过程。当您反序列化同一个对象时,它将在稍后保留其状态。它使您无需手动保存对象的属性即可重新创建对象。
回答by Esko
Serialization is the process of turning a Java object into byte array and then back into object again with its preserved state. Useful for various things like sending objects over network or caching things to disk.
序列化是将 Java 对象转换为字节数组,然后再次返回具有保留状态的对象的过程。适用于各种事情,例如通过网络发送对象或将内容缓存到磁盘。
Read more from this short article which explains programming part of the process quite welland then move over to to Serializable javadoc. You may also be interested in reading this related question.
从这篇简短的文章中阅读更多内容,该文章很好地解释了该过程的编程部分,然后转到Serializable javadoc。您可能也有兴趣阅读此相关问题。
回答by OscarRyz
You can think of serialization as the process of converting an object instance into a sequence of bytes (which may be binary or not depending on the implementation).
您可以将序列化视为将对象实例转换为字节序列(可能是二进制的,也可能不是,取决于实现)的过程。
It is very useful when you want to transmit one object data across the network, for instance from one JVM to another.
当您想通过网络传输一个对象数据时,它非常有用,例如从一个 JVM 传输到另一个 JVM。
In Java, the serialization mechanism is built into the platform, but you need to implement the Serializableinterface to make an object serializable.
在 Java 中,序列化机制内置于平台中,但您需要实现Serializable接口才能使对象可序列化。
You can also prevent some data in your object from being serialized by marking the attribute as transient.
您还可以通过将属性标记为瞬态来防止对象中的某些数据被序列化。
Finally you can override the default mechanism, and provide your own; this may be suitable in some special cases. To do this, you use one of the hidden features in java.
最后,您可以覆盖默认机制,并提供您自己的机制;这可能适用于某些特殊情况。为此,您可以使用java 中的一项隐藏功能。
It is important to notice that what gets serialized is the "value" of the object, or the contents, and not the class definition. Thus methods are not serialized.
需要注意的是,序列化的是对象的“值”或内容,而不是类定义,这一点很重要。因此方法不是序列化的。
Here is a very basic sample with comments to facilitate its reading:
这是一个非常基本的示例,带有注释以方便阅读:
import java.io.*;
import java.util.*;
// This class implements "Serializable" to let the system know
// it's ok to do it. You as programmer are aware of that.
public class SerializationSample implements Serializable {
// These attributes conform the "value" of the object.
// These two will be serialized;
private String aString = "The value of that string";
private int someInteger = 0;
// But this won't since it is marked as transient.
private transient List<File> unInterestingLongLongList;
// Main method to test.
public static void main( String [] args ) throws IOException {
// Create a sample object, that contains the default values.
SerializationSample instance = new SerializationSample();
// The "ObjectOutputStream" class has the default
// definition to serialize an object.
ObjectOutputStream oos = new ObjectOutputStream(
// By using "FileOutputStream" we will
// Write it to a File in the file system
// It could have been a Socket to another
// machine, a database, an in memory array, etc.
new FileOutputStream(new File("o.ser")));
// do the magic
oos.writeObject( instance );
// close the writing.
oos.close();
}
}
When we run this program, the file "o.ser" is created and we can see what happened behind.
当我们运行这个程序时,文件“o.ser”被创建,我们可以看到后面发生了什么。
If we change the value of: someIntegerto, for example Integer.MAX_VALUE, we may compare the output to see what the difference is.
如果我们将someInteger的值更改为,例如Integer.MAX_VALUE,我们可以比较输出以查看不同之处。
Here's a screenshot showing precisely that difference:
这是一个屏幕截图,准确显示了这种差异:
Can you spot the differences? ;)
你能看出区别吗?;)
There is an additional relevant field in Java serialization: The serialversionUIDbut I guess this is already too long to cover it.
Java 序列化中还有一个额外的相关字段:serialversionUID,但我想这已经太长了,无法涵盖它。
回答by Sathesh
Serialization means persisting objects in java. If you want to save the state of the object and want to rebuild the state later (may be in another JVM) serialization can be used.
序列化意味着在java中持久化对象。如果要保存对象的状态,并且想稍后重建状态(可能在另一个JVM中)可以使用序列化。
Note that the properties of an object is only going to be saved. If you want to resurrect the object again you should have the class file, because the member variables only will be stored and not the member functions.
请注意,对象的属性只会被保存。如果你想再次复活对象,你应该有类文件,因为只会存储成员变量而不是成员函数。
eg:
例如:
ObjectInputStream oos = new ObjectInputStream(
new FileInputStream( new File("o.ser")) ) ;
SerializationSample SS = (SearializationSample) oos.readObject();
The Searializable is a marker interface which marks that your class is serializable. Marker interface means that it is just an empty interface and using that interface will notify the JVM that this class can be made serializable.
Searializable 是一个标记接口,用于标记您的类是可序列化的。标记接口意味着它只是一个空接口,使用该接口将通知 JVM 该类可以序列化。
回答by noquery
I liked the way @OscarRyz presents. Although here i am continuing the story of serializationwhich was originally written by @amitgupta.
我喜欢@OscarRyz 呈现的方式。虽然在这里我继续讲述最初由@amitgupta 编写的连载故事。
Even though knowing about the robot class structure and having serialized data Earth's scientist were not able to deserialize the data which can make robots working.
即使了解机器人类结构并序列化数据,地球科学家也无法反序列化可以使机器人工作的数据。
Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
:
Mars's scientists were waiting for the complete payment. Once the payment was done Mars's scientists shared the serialversionUIDwith Earth's scientists. Earth's scientist set it to robot class and everything became fine.
火星的科学家们正在等待全额付款。付款完成后,火星的科学家与地球的科学家共享了serialversionUID。地球科学家将它设置为机器人班,一切都变得很好。
回答by Sindu
Serialization is the process of saving an object in a storage medium (such as a file, or a memory buffer) or to transmit it over a network connection in binary form. The serialized objects are JVM independent and can be re-serialized by any JVM. In this case the "in memory" java objects state are converted into a byte stream. This type of the file can not be understood by the user. It is a special types of object i.e. reused by the JVM (Java Virtual Machine). This process of serializing an object is also called deflating or marshalling an object.
序列化是将对象保存在存储介质(例如文件或内存缓冲区)中或通过网络连接以二进制形式传输对象的过程。序列化的对象独立于 JVM,可以被任何 JVM 重新序列化。在这种情况下,“内存中”java 对象状态被转换为字节流。用户无法理解此类文件。它是一种特殊类型的对象,即被 JVM(Java 虚拟机)重用。这种序列化对象的过程也称为放气或编组对象。
The object to be serialized must implement java.io.Serializable
Interface.
Default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields.
要序列化的对象必须实现java.io.Serializable
接口。对象的默认序列化机制写入对象的类、类签名以及所有非瞬态和非静态字段的值。
class ObjectOutputStream extends java.io.OutputStream implements ObjectOutput,
ObjectOutput
interface extends the DataOutput
interface and adds methods for serializing objects and writing bytes to the file. The ObjectOutputStream
extends java.io.OutputStream
and implements ObjectOutput
interface. It serializes objects, arrays, and other values to a stream. Thus the constructor of ObjectOutputStream
is written as:
ObjectOutput
interface 扩展了DataOutput
接口并添加了用于序列化对象和将字节写入文件的方法。该ObjectOutputStream
扩展java.io.OutputStream
并实现ObjectOutput
对接。它将对象、数组和其他值序列化为流。因此,的构造函数 ObjectOutputStream
写为:
ObjectOutput ObjOut = new ObjectOutputStream(new FileOutputStream(f));
Above code has been used to create the instance of the ObjectOutput
class with the ObjectOutputStream( )
constructor which takes the instance of the FileOuputStream
as a parameter.
上面的代码已用于创建ObjectOutput
类的实例,其中ObjectOutputStream( )
构造函数将 的实例FileOuputStream
作为参数。
The ObjectOutput
interface is used by implementing the ObjectOutputStream
class. The ObjectOutputStream
is constructed to serialize the object.
该ObjectOutput
接口通过实现使用ObjectOutputStream
类。该ObjectOutputStream
构造序列化对象。
Deserializing an Object in java
在java中反序列化一个对象
The opposite operation of the serialization is called deserialization i.e. to extract the data from a series of bytes is s known as deserialization which is also called inflating or unmarshalling.
序列化的相反操作称为反序列化,即从一系列字节中提取数据称为反序列化,也称为膨胀或解组。
ObjectInputStream
extends java.io.InputStream
and implements ObjectInput
interface. It deserializes objects, arrays, and other values from an input stream. Thus the constructor of ObjectInputStream
is written as:
ObjectInputStream
扩展java.io.InputStream
并实现ObjectInput
接口。它从输入流中反序列化对象、数组和其他值。因此,的构造函数 ObjectInputStream
写为:
ObjectInputStream obj = new ObjectInputStream(new FileInputStream(f));
Above code of the program creates the instance of the ObjectInputStream
class to deserialize that file which had been serialized by the ObjectInputStream
class. The above code creates the instance using the instance of the FileInputStream
class which holds the specified file object which has to be deserialized because the ObjectInputStream()
constructor needs the input stream.
上面的程序代码创建了ObjectInputStream
类的实例来反序列化已经被ObjectInputStream
类序列化的文件。上面的代码使用FileInputStream
类的实例创建实例,该类包含必须反序列化的指定文件对象,因为ObjectInputStream()
构造函数需要输入流。
回答by Yash
Java Object Serialization
Java对象序列化
Serialization
is a mechanism to transform a graph of Java objects into an array of bytes for storage(to disk file
) or transmission(across a network
), then by using deserializationwe can restore the graph of objects.
Graphs of objects are restored correctly using a reference sharing mechanism. But before storing, check whether serialVersionUID from input-file/network and .class file serialVersionUID are the same. If not, throw a java.io.InvalidClassException
.
Serialization
是一种将 Java 对象图转换为用于存储 ( to disk file
) 或传输 ( across a network
)的字节数组的机制,然后通过使用反序列化我们可以恢复对象图。使用引用共享机制正确恢复对象图。但是在存储之前,请检查输入文件/网络中的serialVersionUID 和.class 文件serialVersionUID 是否相同。如果没有,抛出一个java.io.InvalidClassException
.
Each versioned class must identify the original class version for which it is capable of writing streams and from which it can read. For example, a versioned class must declare:
serialVersionUID Syntax
// ANY-ACCESS-MODIFIER static final long serialVersionUID = (64-bit has)L; private static final long serialVersionUID = 3487495895819393L;
每个版本化类必须标识它能够为其写入流并可以从中读取的原始类版本。例如,版本化类必须声明:
serialVersionUID 语法
// ANY-ACCESS-MODIFIER static final long serialVersionUID = (64-bit has)L; private static final long serialVersionUID = 3487495895819393L;
serialVersionUIDis essential to the serialization process. But it is optional for the developer to add it into the java source file. If a serialVersionUID is not included, the serialization runtime will generate a serialVersionUID and associate it with the class. The serialized object will contain this serialVersionUID along with other data.
serialVersionUID对序列化过程至关重要。但是开发者可以选择将其添加到java源文件中。如果不包含 serialVersionUID,序列化运行时将生成一个 serialVersionUID 并将其与类相关联。序列化对象将包含此 serialVersionUID 以及其他数据。
Note- It is strongly recommended that all serializable classes explicitly declare a serialVersionUID, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations
, and can thus result in unexpected serialVersionUID conflicts during deserialization, causing deserialization to fail.
注- 强烈建议所有可序列化类显式声明一个 serialVersionUID, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations
,因此可能会在反序列化期间导致意外的 serialVersionUID 冲突,从而导致反序列化失败。
Inspecting Serializable Classes
A Java object is only serializable. if a class or any of its superclasses implements either the java.io.Serializableinterface or its subinterface, java.io.Externalizable.
Java 对象只能序列化。如果一个类或其任何超类实现了java.io.Serializable接口或其子接口java.io.Externalizable。
A class must implement java.io.Serializable interfacein order to serialize its object successfully. Serializable is a marker interface and used to inform the compiler that the class implementing it has to be added serializable behavior. Here Java Virtual Machine (JVM) is responsible for its automatic serialization.
transient Keyword:
java.io.Serializable interface
While serializing an object, if we don't want certain data members of the object to be serialized we can use the transient modifier. The transient keyword will prevent that data member from being serialized.
- Fields declared as transient or static are ignored by the serialization process.
+--------------+--------+-------------------------------------+ | Flag Name | Value | Interpretation | +--------------+--------+-------------------------------------+ | ACC_VOLATILE | 0x0040 | Declared volatile; cannot be cached.| +--------------+--------+-------------------------------------+ |ACC_TRANSIENT | 0x0080 | Declared transient; not written or | | | | read by a persistent object manager.| +--------------+--------+-------------------------------------+
class Employee implements Serializable { private static final long serialVersionUID = 2L; static int id; int eno; String name; transient String password; // Using transient keyword means its not going to be Serialized. }
Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs.
class Emp implements Externalizable { int eno; String name; transient String password; // No use of transient, we need to take care of write and read. @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(eno); out.writeUTF(name); //out.writeUTF(password); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.eno = in.readInt(); this.name = in.readUTF(); //this.password = in.readUTF(); // java.io.EOFException } }
Only objects that support the java.io.Serializable or java.io.Externalizable interface can be
written to
/read from
streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects.
类必须实现java.io.Serializable 接口才能成功序列化其对象。Serializable 是一个标记接口,用于通知编译器实现它的类必须添加可序列化的行为。这里Java虚拟机(JVM)负责其自动序列化。
瞬态关键字:
java.io.Serializable interface
在序列化对象时,如果我们不希望对象的某些数据成员被序列化,我们可以使用瞬态修饰符。瞬态关键字将阻止该数据成员被序列化。
- 序列化过程会忽略声明为瞬态或静态的字段。
+--------------+--------+-------------------------------------+ | Flag Name | Value | Interpretation | +--------------+--------+-------------------------------------+ | ACC_VOLATILE | 0x0040 | Declared volatile; cannot be cached.| +--------------+--------+-------------------------------------+ |ACC_TRANSIENT | 0x0080 | Declared transient; not written or | | | | read by a persistent object manager.| +--------------+--------+-------------------------------------+
class Employee implements Serializable { private static final long serialVersionUID = 2L; static int id; int eno; String name; transient String password; // Using transient keyword means its not going to be Serialized. }
实现 Externalizable 接口允许对象完全控制对象序列化形式的内容和格式。调用 Externalizable 接口的方法 writeExternal 和 readExternal 来保存和恢复对象状态。当由类实现时,它们可以使用 ObjectOutput 和 ObjectInput 的所有方法写入和读取自己的状态。对象负责处理发生的任何版本控制。
class Emp implements Externalizable { int eno; String name; transient String password; // No use of transient, we need to take care of write and read. @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeInt(eno); out.writeUTF(name); //out.writeUTF(password); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.eno = in.readInt(); this.name = in.readUTF(); //this.password = in.readUTF(); // java.io.EOFException } }
只有支持 java.io.Serializable 或 java.io.Externalizable 接口的对象才能是
written to
/read from
流。每个可序列化对象的类都被编码,包括类的类名和签名、对象的字段和数组的值,以及从初始对象引用的任何其他对象的闭包。
Serializable Example For Files
文件的可序列化示例
public class SerializationDemo {
static String fileName = "D:/serializable_file.ser";
public static void main(String[] args) throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
Employee emp = new Employee( );
Employee.id = 1; // Can not Serialize Class data.
emp.eno = 77;
emp.name = "Yash";
emp.password = "confidential";
objects_WriteRead(emp, fileName);
Emp e = new Emp( );
e.eno = 77;
e.name = "Yash";
e.password = "confidential";
objects_WriteRead_External(e, fileName);
/*String stubHost = "127.0.0.1";
Integer anyFreePort = 7777;
socketRead(anyFreePort); //Thread1
socketWrite(emp, stubHost, anyFreePort); //Thread2*/
}
public static void objects_WriteRead( Employee obj, String serFilename ) throws IOException{
FileOutputStream fos = new FileOutputStream( new File( serFilename ) );
ObjectOutputStream objectOut = new ObjectOutputStream( fos );
objectOut.writeObject( obj );
objectOut.close();
fos.close();
System.out.println("Data Stored in to a file");
try {
FileInputStream fis = new FileInputStream( new File( serFilename ) );
ObjectInputStream ois = new ObjectInputStream( fis );
Object readObject;
readObject = ois.readObject();
String calssName = readObject.getClass().getName();
System.out.println("Restoring Class Name : "+ calssName); // InvalidClassException
Employee emp = (Employee) readObject;
System.out.format("Obj[No:%s, Name:%s, Pass:%s]", emp.eno, emp.name, emp.password);
ois.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void objects_WriteRead_External( Emp obj, String serFilename ) throws IOException {
FileOutputStream fos = new FileOutputStream(new File( serFilename ));
ObjectOutputStream objectOut = new ObjectOutputStream( fos );
obj.writeExternal( objectOut );
objectOut.flush();
fos.close();
System.out.println("Data Stored in to a file");
try {
// create a new instance and read the assign the contents from stream.
Emp emp = new Emp();
FileInputStream fis = new FileInputStream(new File( serFilename ));
ObjectInputStream ois = new ObjectInputStream( fis );
emp.readExternal(ois);
System.out.format("Obj[No:%s, Name:%s, Pass:%s]", emp.eno, emp.name, emp.password);
ois.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Serializable Example Over Network
网络上的可序列化示例
Distributing object's state across different address spaces, either in different processes on the same computer, or even in multiple computers connected via a network, but which work together by sharing data and invoking methods.
将对象的状态分布在不同的地址空间中,可以是在同一台计算机上的不同进程中,也可以是在通过网络连接的多台计算机中,但它们通过共享数据和调用方法一起工作。
/**
* Creates a stream socket and connects it to the specified port number on the named host.
*/
public static void socketWrite(Employee objectToSend, String stubHost, Integer anyFreePort) {
try { // CLIENT - Stub[marshalling]
Socket client = new Socket(stubHost, anyFreePort);
ObjectOutputStream out = new ObjectOutputStream(client.getOutputStream());
out.writeObject(objectToSend);
out.flush();
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Creates a server socket, bound to the specified port.
public static void socketRead( Integer anyFreePort ) {
try { // SERVER - Stub[unmarshalling ]
ServerSocket serverSocket = new ServerSocket( anyFreePort );
System.out.println("Server serves on port and waiting for a client to communicate");
/*System.in.read();
System.in.read();*/
Socket socket = serverSocket.accept();
System.out.println("Client request to communicate on port server accepts it.");
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
Employee objectReceived = (Employee) in.readObject();
System.out.println("Server Obj : "+ objectReceived.name );
socket.close();
serverSocket.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
@see
@看
回答by VdeX
Daring to answer the 6-year-old question, adding just a very high-level understanding for people new to Java
敢于回答6年前的问题,只是为Java新手增加了一个非常高层次的理解
What is Serialization?
什么是序列化?
Converting an object to bytes
将对象转换为字节
What is Deserialization?
什么是反序列化?
Converting bytes back to an object (Deserialization).
将字节转换回对象(反序列化)。
When is serialization used?
什么时候使用序列化?
When we want to Persist the Object. When we want the object to exist beyond the lifetime of the JVM.
当我们想要持久化对象时。当我们希望对象存在于 JVM 的生命周期之外时。
Real World Example:
真实世界示例:
ATM: When the account holder tries to withdraw money from the server through ATM, the account holder information like withdrawal details will be serialized and sent to the server where the details are deserialized and used to perform operations.
ATM:当账户持有人试图通过ATM从服务器取款时,账户持有人信息如取款明细将被序列化并发送到细节被反序列化并用于执行操作的服务器。
How serialization is performed in java.
java中如何进行序列化。
Implement
java.io.Serializable
interface (marker interface so no method to implement).Persist the object: Use
java.io.ObjectOutputStream
class, a filter stream which is a wrapper around a lower-level byte stream (to write Object to file systems or transfer a flattened object across a network wire and rebuilt on the other side).writeObject(<<instance>>)
- to write an objectreadObject()
- to read an serialized Object
实现
java.io.Serializable
接口(标记接口所以没有实现方法)。持久化对象:使用
java.io.ObjectOutputStream
类,过滤器流,它是低级字节流的包装器(将对象写入文件系统或通过网络传输扁平对象并在另一侧重建)。writeObject(<<instance>>)
- 写一个对象readObject()
- 读取序列化对象
Remember:
记住:
When you serialize an object, only the object's state will be saved, not the object's class file or methods.
序列化对象时,只会保存对象的状态,而不保存对象的类文件或方法。
When you serialized a 2-byte object, you see 51 bytes serialized file.
当您序列化一个 2 字节的对象时,您会看到 51 字节的序列化文件。
Steps how the object is serialized and de-serialized.
逐步说明对象的序列化和反序列化方式。
Answer for: How did it convert to 51 bytes file?
回答:它是如何转换为 51 字节文件的?
- First writes the serialization stream magic data (STREAM_MAGIC= "AC ED" and STREAM_VERSION=version of the JVM).
- Then it writes out the metadata of the class associated with an instance (length of the class, the name of the class, serialVersionUID).
- Then it recursively writes out the metadata of the superclass until it finds
java.lang.Object
. - Then starts with the actual data associated with the instance.
- Finally writes the data of objects associated with the instance starting from metadata to the actual content.
- 首先写入序列化流魔术数据(STREAM_MAGIC=“AC ED”和STREAM_VERSION=JVM的版本)。
- 然后它写出与实例关联的类的元数据(类的长度、类的名称、serialVersionUID)。
- 然后它递归地写出超类的元数据,直到找到
java.lang.Object
。 - 然后从与实例关联的实际数据开始。
- 最后将与实例关联的对象的数据从元数据开始写入实际内容。
If you are interested in more in-depth information about Java Serialization please check this link.
如果您对 Java 序列化的更深入信息感兴趣,请查看此链接。
Edit: One more good linkto read.
编辑:还有一个很好的链接可供阅读。
This will answer a few frequent questions:
这将回答一些常见问题:
How not to serialize any field in class.
Ans: use transient keywordWhen child class is serialized does parent class get serialized?
Ans: No, If a parent is not extending the Serializable interface parents field don't get serialized.When a parent is serialized does child class get serialized?
Ans: Yes, by default child class also gets serialized.How to avoid child class from getting serialized?
Ans: a. Override writeObject and readObject method and throwNotSerializableException
.b. also you can mark all fields transient in child class.
- Some system-level classes such as Thread, OutputStream, and its subclasses, and Socket are not serializable.
如何不序列化类中的任何字段。
Ans:使用transient关键字当子类被序列化时,父类会被序列化吗?
回答:不,如果父级未扩展 Serializable 接口的父级字段,则不会被序列化。当父类被序列化时,子类会被序列化吗?
Ans:是的,默认情况下子类也会被序列化。如何避免子类被序列化?
答: A. 覆盖 writeObject 和 readObject 方法并 throwNotSerializableException
。湾 您也可以在子类中标记所有字段为瞬态。
- 一些系统级类,例如 Thread、OutputStream 及其子类和 Socket,是不可序列化的。