Java中transient有何作用?

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;
}
@Override
public String toString() {
// TODO Auto-generated method stub
StringBuffer sb = new StringBuffer();
sb.append("姓名:"+name+",");
sb.append("年龄:"+age+"\n");
return sb.toString();
}
@Override
protected Employee clone() {
// TODO Auto-generated method stub
Employee employss = null; ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(this);
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.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 block
e.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
上一篇:kafka系列教程2(设计构造及原理1)


下一篇:html5文本框提示文字属性为placeholder