序列化

作者: Minstrel_a7ca | 来源:发表于2018-07-21 11:46 被阅读0次

    序列化是把对象转换成存储或传输格式的过程。
    反序列化就是从文件或输入流获取对象。

    Serializable接口

    JAVA中只有实现了Serializable接口的类才可以实例化。
    这个接口没有方法和字段,只是起标识作用。

    transient关键字

    transient关键字表示该字段是短暂的,不需要序列化,比如密码字段,敏感信息字段。
    writeObject不会将此字段的值写出。
    只有在类实现了Serializable接口才有意义。

    读写

    通过ObjectOutputStreamObjectInPutStream

    写实例

            FileOutputStream fos = new FileOutputStream("t.tmp");
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject("Today");
            oos.writeObject(new Date());
            oos.close();
    

    读实例

    与上面写相对应

            FileInputStream fis = new FileInputStream("t.tmp");
            ObjectInputStream ois = new ObjectInputStream(fis);
            String today = (String) ois.readObject();
            Date date = (Date) ois.readObject();
            ois.close();
    

    防止对单例模式的破坏

    在单例中添加readResolve方法。

    class Singleton
    {
       private volatile static Singleton singleton;
        private Singleton (){}
        public static Singleton getSingleton() {
            if (singleton == null) {
                synchronized (Singleton.class) {
                    if (singleton == null) {
                        singleton = new Singleton();
                    }
                }
            }
            return singleton;
        }
       private Object readResolve() {
            return singleton;
        }
    }
    

    相关文章

      网友评论

          本文标题:序列化

          本文链接:https://www.haomeiwen.com/subject/cbchmftx.html