认识 transient !

作用:

transient关键字修改的变量不会被序列化!


package discovery.transientTest;
import java.io.Serializable;
public class Transient implements Serializable{
    private static final long serialVersionUID = 1L;
    private transient int i = 0;
    private int j = 0;
    public Transient(int i,int j){
        this.i = i;
        this.j = j;
    }
    public String toString(){
        return "i = " + i + ", j = " + j;
    }
}

package discovery.transientTest;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
 * 被transient修饰的变量不能被序列化
 */

public class Client {
    public static void main(String[] args) throws Exception {
        Client tt = new Client();
        tt.test();
    }
    public void test() throws Exception {
        Transient ti = new Transient(45); 
        System.out.println(ti.toString()); 
        ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("D:/ti.out"));
        o.writeObject(ti); 
        o.close(); 
        ObjectInputStream in =new ObjectInputStream(new FileInputStream("D:/ti.out")); 
        Transient logInfo = (Transient)in.readObject(); 
        System.out.println(logInfo.toString()); 
    }
}

输出:
= 4, j = 5
= 0, j = 5






posted @ 2014-02-14 23:04  龍變  阅读(182)  评论(0编辑  收藏  举报