transient關鍵字

     java的transient關鍵字爲咱們提供了便利,你只須要實現Serilizable接口,將不須要序列化的屬性前添加關鍵字transient,序列化對象的時候,這個屬性就不會序列化到指定的目的地中。java

     

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;
	}
}

 運行結果:this

a = 25,b = 張三
a = 25,b = null
相關文章
相關標籤/搜索