標籤:
transient關鍵字用來防止序列化域。如果一個參考型別被transient修飾,則其還原序列化的結果是null。基本類型則為0。如果參考型別時不可序列化的類,則也應該使用transient修飾,它在還原序列化時會被直接跳過。
可以用transient來修飾不想儲存的域
下面的例子可以看到被transient修飾的name,使用序列化複製後,還原序列化的結果是null
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 age) {this.age = age;}@Overridepublic String toString() {// TODO Auto-generated method stubStringBuffer sb = new StringBuffer();sb.append("姓名:"+name+",");sb.append("年齡:"+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);oos.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 { public static void main(String[] args) { Employee emp = new Employee("阿坤", 21); System.out.println(emp); Employee emp1 = emp.clone(); System.out.println(emp1); }}
姓名:阿坤,年齡:21姓名:null,年齡:21
Java中transient有何作用?