Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Serializable interface of Java

2025-04-08 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to use the Serializable interface of Java". In the daily operation, I believe many people have doubts about how to use the Serializable interface of Java. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use the Serializable interface of Java". Next, please follow the editor to study!

1. Serializable: serialization

1. Serializable is located in the java.io package and provides a semantic-level interface for serializing Java classes. There are no methods or fields, just to identify serializable semantics.

2. If some fields in the class do not want to be serialized, you can modify them with the keyword: transient.

3. Serialization can be realized through ObjectOutputStream, and deserialization can be realized through ObjectInputStream.

4. Custom serialization API: Externalizable

5. Serialization: for network transmission (RPC remote call); saving objects to disk (passivation and activation of tomcat)

6. Use suggestion: to implement the serialization interface, please add:

Private static final long serialVersionUID = 1L

7. It can be used directly through serialized byte stream.

/ / serialize the object itself to the byte stream ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream (); ObjectOutputStream objectOutputStream = new ObjectOutputStream (byteArrayOutputStream); objectOutputStream.writeObject (this); / / then deserialize the byte stream to get a copy of the object ObjectInputStream objectInputStream = new ObjectInputStream (new ByteArrayInputStream (byteArrayOutputStream.toByteArray ())); Object object = objectInputStream.readObject ()

8. Use the java command: serialver [- classpath classpath] [- show] [classname...] View the serialized values of a class

The-classpath option specifies where to look for the classes (in directories or jar files, separated by semicolon marks;).

The-show option displays a simple user interface that allows the user to enter a full class name and then press Enter key or click Show button to display the serialVersionUID number.

Example:

/ / win+R Open cmd and enter the following command: serialver-classpath E:\ j2se-example\ target\ classes net.liuzd.j2se.example.copy.MyDong

2. Examples

1. Test class

1.1 Code example

Package net.liuzd.j2se.example.copy;import java.io.*;public class DongSerializableTest {static String fileName = "dong.ser"; public static void main (String [] args) throws Exception {Dong dong = new Dong (); dong.setName ("Yang Guo"); dong.setAge (19); / / ObjectOutputStream outputStream = new ObjectOutputStream (new FileOutputStream (fileName)); outputStream.writeObject (dong); outputStream.close (); / / ObjectInputStream inputStream = new ObjectInputStream (new FileInputStream (fileName); Dong readDong = (Dong) inputStream.readObject ()) System.out.println (readDong);} class Dong implements Serializable {private String name;private int age;public Dong () {} public String getName () {return name;} public void setName (String name) {this.name = name;} public int getAge () {return age;} public void setAge (int age) {this.age = age;} @ Overridepublic String toString () {return "Dong {" + "name='" + name +'\'+ ", age=" + age +'}';}}

1.2 after running, the result is printed successfully: Dong {name=' Yang', age=19}

2. Add another attribute to the test class

Add another attribute to the test class: sex and its corresponding get,set method, overriding the toString () method.

Private int sex;public int getSex () {return sex;} public void setSex (int sex) {this.sex = sex;} @ Overridepublic String toString () {return "Dong {" + "name='" + name +'\'+ ", age=" + age + ", sex=" + sex +'}';}

2.2 Direct operation method:

ObjectInputStream inputStream = new ObjectInputStream (new FileInputStream (fileName)); Dong readDong = (Dong) inputStream.readObject (); System.out.println (readDong)

2.3 found that there was an error:

Exception in thread "main" java.io.InvalidClassException: net.liuzd.j2se.example.copy.Dong Local class incompatible: stream classdesc serialVersionUID = 2001103299326914393 Local class serialVersionUID = 1180199239641161346at java.io.ObjectStreamClass.initNonProxy (ObjectStreamClass.java:699) at java.io.ObjectInputStream.readNonProxyDesc (ObjectInputStream.java:1963) at java.io.ObjectInputStream.readClassDesc (ObjectInputStream.java:1829) at java.io.ObjectInputStream.readOrdinaryObject (ObjectInputStream.java:2120) at java.io.ObjectInputStream.readObject0 (ObjectInputStream.java:1646) at java.io.ObjectInputStream.readObject (ObjectInputStream.java:482) at java.io.ObjectInputStream.readObject (ObjectInputStream.java:440) at net.liuzd.j2se.example.copy.DongSerializableTest.main (DongSerializableTest.java:20)

2.4 problems identified:

2.4.1. We didn't specify that serialVersionUID,JDK8 automatically generated a

2.4.2. The inconsistency between the two serialVersionUID was found, which led to the running error.

2.5 View API: serializable documentation

2.5.1 explicitly states the need for us to explicitly declare as: private static final long serialVersionUID, which is of no use to inherited members.

2.5.2 the default serialVersionUID value is highly sensitive to class details, which may vary from compiler to compiler and may result in unexpected results: InvalidClassException

2.5.3 one of the document notes:

If a serializable class does not explicitly declare a serialVersionUID, thenthe serialization runtime will calculate a default serialVersionUID valuefor that class based on various aspects of the class, as described in theJava (TM) Object Serialization Specification. However, it is stronglyrecommended that all serializable classes explicitly declareserialVersionUID values, since the default serialVersionUID computation ishighly sensitive to class details that may vary depending on compilerimplementations, and can thus result in unexpectedInvalidClassExceptions during deserialization. Therefore, toguarantee a consistent serialVersionUID value across different java compilerimplementations, a serializable class must declare an explicitserialVersionUID value. It is also strongly advised that explicitserialVersionUID declarations use the private modifier wherepossible, since such declarations apply only to the immediately declaringclass--serialVersionUID fields are not useful as inherited members. Arrayclasses cannot declare an explicit serialVersionUID, so they always havethe default computed value, but the requirement for matchingserialVersionUID values is waived for array classes.

2.6 practice

2.6.1 only the serialVersionUID attribute is added

What if we only specify serialVersionUID in 1. 1 and try again? (no sex added)

Procedure: our class in 1. 1: Dog adds the serialVersionUID attribute.

Private static final long serialVersionUID = 1L

Run the result again: as shown in 1.2.

2.6.2 repeat step 2.1, everything else remains the same.

2.6.3 repeat step 2.2, run the result: correct!

Dong {name=' Yang Guo', age=19, sex=0}

At this point, the study on "how to use the Serializable interface of Java" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report