transient 关键字的简单用法

来源:互联网 发布:华为云计算招聘 编辑:程序博客网 时间:2024/06/16 00:21

  我们都知道一个对象只要实现了Serilizable接口,这个对象就可以被序列化。

在实际中我们可能会遇到有部分属性需要序列化,部分属性不需要序列化的问题,这时需要使用transient来做。

main方法如下:

package com.examplexue;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.ObjectOutputStream;public class main {    public static void main(String[] args){        testClass test = new testClass();        test.setTest1("test1");        test.setTest2("test2");        //输出读取前设置的字符        System.out.println("test1: " + test.getTest1());        System.err.println("test2: " + test.getTest2());        try {            //创建文件test.txt            ObjectOutputStream os = new ObjectOutputStream(                    new FileOutputStream("D:/test.txt"));            os.writeObject(test); // 将test对象写进文件            os.flush();            os.close();        }catch (FileNotFoundException e) {            e.printStackTrace();        }catch (IOException e) {            e.printStackTrace();        }        System.out.println("===========================================");        //下面是输出文件内容        try {            ObjectInputStream is = new ObjectInputStream(new FileInputStream(                    "D:/test.txt"));            test = (testClass) is.readObject(); // 从流中读取User的数据            is.close();            //输出从文件中取出            System.out.println("test1: " + test.getTest1());            System.err.println("test2: " + test.getTest2());        } catch (FileNotFoundException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } catch (ClassNotFoundException e) {            e.printStackTrace();        }    }    }



类testClass如下:

package com.examplexue;import java.io.Serializable;public class testClass implements Serializable {    private String test1;    private transient String test2;    public void setTest1(String test1) {        this.test1 = test1;    }    public void setTest2(String test2) {        this.test2 = test2;    }    public String getTest1() {        return test1;    }    public String getTest2() {        return test2;    }}


输出结果如下:


test1: test1
test2: test2
===========================================
test2: null
test1: test1



以上就是 transient 关键字的简单用法

原创粉丝点击