transient keyword in Java

Introduction to keywords

As long as an object implements the Serilizable interface, the object can be serialized. This serialization mode of java provides a lot of convenience for developers, and the specific serialization process does not need to be related. As long as the class implements the Serilizable interface, the All properties and methods are automatically serialized. But there is a case where some attributes do not need a serial number, so this keyword is used. You only need to implement the Serilizable interface, and add the keyword transient before the properties that do not need to be serialized . When serializing the object, this property will not be serialized to the specified destination.

Code:

The UserInfo class that implements the Serializable interface and has a property modified by the transient keyword


package com.testtransient.model;


import java.io.Serializable;


public class UserInfo implements Serializable {


private static final long serialVersionUID = 1L;


private String name;


private transient String pwd;


public UserInfo(String name, String pwd) {
this.name = name;
this.pwd = pwd;
}


public String toString() {
return "name=" + name + ",psw=" + pwd;
}
}


Test programs written through input and output streams

package com.testtransient.model;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class TestTransient {
public static void main(String[] args) {
UserInfo userInfo = new UserInfo("张三", "123456");
System.out.println(userInfo);
try {
// Serialization, properties set to transient are not serialized
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(
"UserInfo.out"));
o.writeObject(userInfo);
o.close();
} catch (Exception e) {
e.printStackTrace ();
}
try {
// reread the content
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"UserInfo.out"));
UserInfo readUserInfo = (UserInfo) in.readObject();
// The content of psw after reading is null
System.out.println(readUserInfo.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}




从上面结果能够看出来经过transient关键字修饰的字段是不能够被序列化的。




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325748844&siteId=291194637