The transient keyword is used to prevent serialization of a domain. If a reference type is transient decorated, the result of deserialization is null. The base type is 0. If a class is not serializable when referencing a type, you should also use the transient adornment, which is skipped directly when deserializing.
You can use transient to modify fields that you do not want to save
The following example shows the name modified by transient, and the deserialized result is null after using a serialized clone
Package Com.lk.b;import Java.io.bytearrayinputstream;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.io.objectinputstream;import Java.io.objectoutputstream;import Java.io.serializable;public class Employee implements cloneable,serializable{private static final long Serialversionuid = 1l;private transient string name;private int age;public Employee (String name,int age) {this.name = name; This.age = age;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;} public int getage () {return age;} public void Setage (int.) {this.age = age;} @Overridepublic String toString () {//TODO auto-generated method Stubstringbuffer sb = new StringBuffer (); Sb.append ("Name:" +name+ ","); Sb.append ("Age:" +age+ "\ n"); return sb.tostring (); @Overrideprotected Employee Clone () {//TODO auto-generated method Stubemployee Employss = null; Bytearrayoutputstream BAOs = new Bytearrayoutputstream (); try {objectoutputstream oos = new ObjectOutputStream (BAOs); o Os.writEobject (this); Oos.close ();} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();} Bytearrayinputstream Bais = new Bytearrayinputstream (Baos.tobytearray ()); try {ObjectInputStream ois = new ObjectInputStream (Bais); Employss = (Employee) ois.readobject (); Ois.close ();} catch (IOException | ClassNotFoundException e) {//TODO auto-generated catch Blocke.printstacktrace ();} return Employss;}}
Package com.lk.b; Public class TEST3 { publicstaticvoid main (string[] args) { new Employee ("Akkun", +); SYSTEM.OUT.PRINTLN (EMP); = Emp.clone (); System.out.println (EMP1); }}
Name: Akkun, Age: + name:null, Age: 21
What does transient in Java do?