transient关键字

     java的transient关键字为我们提供了便利,你只需要实现Serilizable接口,将不需要序列化的属性前添加关键字transient,序列化对象的时候,这个属性就不会序列化到指定的目的地中。

     

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Test {
	public static void main(String[] args) throws FileNotFoundException,
			IOException, ClassNotFoundException {
		A a = new A(25, "张三");
		System.out.println(a);
		
		
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c://mm.txt"));
		oos.writeObject(a);
		oos.close();
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c://mm.txt"));
		a = (A) ois.readObject();
		System.out.println(a);

	}

}

class A implements Serializable {
	int a;
	transient String b; //transient  使b属性没有进行序列化

	public A(int a, String b) {
		this.a = a;
		this.b = b;
	}

	public String toString() {
		return "a = " + a + ",b = " + b;
	}
}

 运行结果:

a = 25,b = 张三
a = 25,b = null

  

 

 

posted @ 2014-07-14 16:03  小子582547523  阅读(329)  评论(0编辑  收藏  举报