Java Study Notes (17th) -- java serialization

Source: Internet
Author: User
Tags object serialization

There is always a lot of things to be used for project development. It is not a short time for a new knowledge to come out, but a new one for yourself. Therefore, you need to learn it by yourself, it is hoped that the learning efficiency will be improved in the future. This article is about Java serialization and is optional. [Knowledge point] 1. What is serialization? We all know that objects are temporarily stored in the memory and cannot be taken away by using a USB flash drive. Sometimes, to transfer objects using media and keep the object state, you need to save the objects, this process is called serialization. The popular point is to collapse the soul of a person (object) into a stone (a media that can be transmitted ). Ii. What is deserialization? It is the process of restoring things in the media to objects and stones to adults. Iii. Possible usage 1. when you want to write the objects in the memory to the hard disk, for example, if your memory is insufficient, the computer will temporarily save some objects in the memory to the hard disk, when it is used, it is read into the memory. The storage space of the hard disk is called virtual memory. For example, if you want to save a specific object to a file and I will use it several days later, you need to implement the Serializable interface; 2. when you want to use a Socket to transmit objects over the network, you may need to implement the Serializable interface when programming java Socket; the most common one is to transmit a string. It is a class in JDK and also implements the Serializable interface, so it can be transmitted over the network. 3. when you want to transmit objects through RMI, if you want to call a remote object method through remote method call (RMI, for example, if you call the method of the object of another computer B in computer A, you need to obtain the reference of the object of computer B through the JNDI service, and transfer the object from B to, you need to implement the serialization interface. Iv. Serializable interface: an object serialization interface. Only the Serializable interface is implemented for a class, and its objects are Serializable. Therefore, to serialize objects of some classes, these classes must implement the Serializable interface. Serializable implementation code: 1 public interface Serializable {2} can be seen that the Serializable interface is an empty interface, only one purpose is to indicate that the object of a class can be serialized. This label is a feature that the class can be serialized, indicating that the class can be serialized. 5. Externalizable interface: Externalizable, a subclass of the Serializable interface. Implementation Code: 1 public interface Externalizable extends java. io. serializable {2 void writeExternal (ObjectOutput out) throws IOException; 3 void readExternal (ObjectInput in) throws IOException, ClassNotFoundException; 4} 6. Differences between the Serializable interface and Externalizable interface Serializable: to serialize an object, its class must implement this interface. All attributes of this object (including private attributes and referenced objects) can be serialized and deserialized to save and pass. Externalizable: This is a subclass of the Serializable interface. Sometimes we do not want to serialize so many objects. You can use this interface. The writeExternal () and readExternal () methods of this interface can specify the attributes to be serialized; [learning demo And explanation] 1. Java serialization 1. java. io. objectOutputStream indicates the Object output stream. Its writeObject (Object obj) method serializes the obj Object specified by the parameter and writes the obtained byte sequence to a target output stream. 2. java. io. ObjectInputStream indicates the input stream of the object. Its readObject () method reads the byte sequences from a source input stream, deserializes them into an object, and returns it. 3. object serialization includes the following steps: 1) create an object output stream, which can wrap a target output stream of another type, such as a file output stream; 2) use the writeObject () of the object output stream () method write object. 4. the steps for object deserialization are as follows: 1) create an object input stream, which can wrap a source input stream of another type, such as a file input stream; 2) read object () through the object input stream () method To Read objects. 5. code implementation: SerializableTest. java copy code 1 import java. io. *; 2 import java. util. date; 3 4 public class SerializableTest {5 6 public static void main (String [] args) throws Exception {7 ObjectOutputStream out = new ObjectOutputStream (new FileOutputStream ("objectFile. obj "); 8 // serialize object 9 Customer customer Customer = new Customer (" A honey fruit ", 24); 10 out. writeObject ("Hello! "); 11 out. writeObject (new Date (); 12 out. writeObject (customer); // write the serialized object 13 out. writeInt (123); // write data of the basic type 14 out. close (); 15 // deserialization object 16 ObjectInputStream in = new ObjectInputStream (new FileInputStream ("objectFile. obj "); 17 System. out. println ("obj1 =" + (String) in. readObject (); 18 System. out. println ("obj2 =" + (Date) in. readObject (); 19 Customer obj3 = (Customer) in. readObject (); 20 System. out. printl N ("obj3 =" + obj3); 21 int obj4 = in. readInt (); 22 System. out. println ("obj4 =" + obj4); 23 in. close (); 24} 25} 26 class Customer implements Serializable {27 private String name; 28 private int age; 29 public Customer (String name, int age) {30 this. name = name; 31 this. age = age; 32} 33 public String toString () {34 return "name =" + name + ", age =" + age; 35} 36} copy Code 6. running result: 1 obj1 = hello! 2 obj2 = Thu Apr 03 09:12:09 CST 20143 obj3 = name = honey fruit, age = 244 obj4 = 123 2. Use the keyword 1 when implementing serialization in Java. transient is a keyword of the Java language used to indicate that a domain is not part of the object serialization. When an object is serialized, the value of the transient variable is not included in the serialized representation. However, non-transient variables are included. 2. In the demo code, the Password is defined as the transient type and will not be serialized during output. The output is null. SerializableTest. java copy code 1 import java. io. *; 2 3 public class SerializableTest {4 public static void main (String args []) {5 testObjectSeri (); 6 testObjectInSeri (); 7} 8/** 9 * Object serialization test 10 */11 public static void testObjectSeri () {12 Person person = new Person ("lava", "341022225562156 ", "lavasoft"); 13 FileOutputStream fos = null; 14 ObjectOutputStream oos = null; 15 try {16 fos = new FileOut PutStream ("person. dat "); 17 oos = new ObjectOutputStream (fos); 18 oos. writeObject (person); 19} catch (FileNotFoundException e) {20 System. out. println ("the specified file cannot be found! "); 21 e. printStackTrace (); 22} catch (IOException e) {23 e. printStackTrace (); 24} finally {25 try {26 oos. flush (); 27 oos. close (); 28} catch (IOException e) {29 e. printStackTrace (); 30} 31} 32} 33/** 34 * object deserialization Test 35 */36 public static void testObjectInSeri () {37 FileInputStream FCM = null; 38 ObjectInputStream ois = null; 39 Person person = null; 40 try {41 Fi = new FileInputStream ("Person. dat "); 42 ois = new ObjectInputStream (FCM); 43 person = (Person) ois. readObject (); 44} catch (FileNotFoundException e) {45 e. printStackTrace (); 46} catch (IOException e) {47 e. printStackTrace (); 48} catch (ClassNotFoundException e) {49 e. printStackTrace (); 50} finally {51 try {52 ois. close (); 53} catch (IOException e) {54 e. printStackTrace (); 55} 56} 57 System. out. println (per Son. toString (); 58} 59} 60/** 61 * class 62 */63 class Person implements Serializable {64 private String username; 65 private String cardNumber; 66 private transient String password; 67 public Person (String username, String cardNumber, String password) {68 this. username = username; 69 this. cardNumber = cardNumber; 70 this. password = password; 71} 72 public String getUsername () {73 ret Urn username; 74} 75 public void setUsername (String username) {76 this. username = username; 77} 78 public String getCardNumber () {79 return cardNumber; 80} 81 public void setCardNumber (String cardNumber) {82 this. cardNumber = cardNumber; 83} 84 public String getPassword () {85 return password; 86} 87 public void setPassword (String password) {88 this. password = password; 89} 90 public Str Ing toString () {91 StringBuffer sb = new StringBuffer (this. getClass (). getName (); 92 sb. append ("["); 93 sb. append ("\ n \ t"); 94 sb. append ("username =" + this. username); 95 sb. append ("\ n \ t"); 96 sb. append ("cardNumber =" + this. cardNumber); 97 sb. append ("\ n \ t"); 98 sb. append ("password =" + this. password); 99 sb. append ("]"); 100 return sb. toString (); 101} 102} copy code 4. running result: 1 Person [2 username = lava 3 cardN Umber = 3410222255621564 password = null] [several problems] I. serialized version: serialVersionUID 1. serialVersionUID: To maintain version compatibility during serialization, deserialization maintains the uniqueness of objects during version upgrade. The default value of serialVersionUID of the class is completely dependent on the implementation of the Java compiler. For the same class, compiling with different Java compilers may lead to different serialVersionUID and may also be the same. To improve the independence and certainty of serialVersionUID, we strongly recommend that you define serialVersionUID displayed in a serializable class and assign it a clear value. Explicitly defining serialVersionUID has two purposes: 1) In some cases, different versions of the class must be compatible with serialization. Therefore, ensure that different versions of the class have the same serialVersionUID; 2) in some cases, different versions of the class are not required to be compatible with serialization. Therefore, make sure that different versions of the class have different serialVersionUID. 2. there are two generation methods: one is the default 1L, for example, private static final long serialVersionUID = 1L; one is to generate a 64-bit hash field based on the class name, Interface Name, member method, and attribute, for example, private static final long serialVersionUID = xxxxL; if a class implements the Serializable interface and serialVersionUID is not defined, Eclipse will provide this interface. The prompt function tells you to define it. In Eclipse, click the "warning" icon in the class, and Eclipse will automatically generate the two methods. If you do not want to define it, you can disable it in Eclipse settings as follows: window ==> Preferences ==> Java ==> Compiler ==> Error/Warnings ==> Potential programming problems change the Serializable class without serialVersionUID's warning to ignore. Ii. Other Instructions: The data of the basic type can be serialized directly. Its Class must implement the Serializable interface. If a class contains instance variables of the reference type, this reference type must also implement the Serializable interface. If you do not want the reference class to implement the Serializable interface and the class can be serialized successfully, use the transient keyword.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.