首页 > 其他 > 详细

transient关键字

时间:2014-08-21 18:32:54      阅读:267      评论:0      收藏:0      [点我收藏+]

当使用Serializable接口实现序列化操作时,如果一个对象中的某个属性不希望被序列化,

则可以使用transient关键字进行声明:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;

class Person implements Serializable {
    private transient String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String toString() {
        return "NAME: " + this.name + ": AGE: " + this.age;
    }
}

public class SerDemo01 {
    public static void main(String[] args) throws Exception {
        ser();
        dser();
    }

    public static void ser() throws Exception {
        File f = new File("F:" + File.separator + "watasi.txt");
        ObjectOutputStream oos = null;
        OutputStream out = new FileOutputStream(f);
        oos = new ObjectOutputStream(out);
        oos.writeObject(new Person("frank", 30));
        oos.close();
    }

    public static void dser() throws Exception {
        File f = new File("F:" + File.separator + "watasi.txt");
        ObjectInputStream ois = null;
        InputStream input = new FileInputStream(f);
        ois = new ObjectInputStream(input);
        Object obj = ois.readObject();
        ois.close();
        System.out.println(obj);
    }
}

transient关键字,布布扣,bubuko.com

transient关键字

原文:http://www.cnblogs.com/vonk/p/3927532.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!