在开发过程中,有时候需要对对象序列化,JAVA提供了Serializable接口来实现序列化。而在实际使用过程中有可能某个对象的某个属性不需要序列化,这时候关键字transient就可以使这个属性不进行序列化。
创建一个Person类
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private transient String address;//address字段加上了transient关键字,表明该字段不需要序列化
public Person(String name,String address){
this.name = name;
this.address = address;
}
public String toString(){
return "name="+this.name+", address="+this.address;
}
}
测试类‘
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Test {
public static void main(String[] args){
Person person = new Person("aMan","chongqing");
System.out.println(person);
try{
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("Person.out"));
o.writeObject(person);
o.close();
}catch (Exception e){
e.printStackTrace();
}
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("Person.out"));
Person inPerson = (Person)in.readObject();
System.out.println(inPerson);
}catch (Exception e){
e.printStackTrace();
}
}
}
输出结果
name=aMan, address=chongqing
name=aMan, address=null
可以看到直接输出Person对象时,address字段不为null,而通过输出输入流序列化后,address字段为null。