Java - Serializable 和 Externalizable

参考

Serializable接口

如果一个类要支持序列化, 必须得实现Serializable接口. 该接口仅仅是一个标记, 没有声明任何方法.

serialVersionUID 属性:

 * The serialization runtime associates with each serializable class a version
 * number, called a serialVersionUID, which is used during deserialization to
 * verify that the sender and receiver of a serialized object have loaded
 * classes for that object that are compatible with respect to serialization.
 * If the receiver has loaded a class for the object that has a different
 * serialVersionUID than that of the corresponding sender's class, then
 * deserialization will result in an {@link InvalidClassException}.  A
 * serializable class can declare its own serialVersionUID explicitly by
 * declaring a field named <code>"serialVersionUID"</code> that must be static,
 * final, and of type <code>long</code>:
 *
 * <PRE>
 * ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
 * </PRE>

这个属性可以有任何的访问修饰符, 不过要是static final long, 这是一个版本标记, 因为可能这个类可能存在新旧版本, 所以使用该标记来标明. 如果收发方的这个类版本不一致, 在反序列化 (deserialization) 的时候就会抛出InvalidClassException异常.

没有实现Serializable接口的例子

内部类NonSerializable没有实现Serializable接口, Item类实现了该接口, 但是有一个NonSerializable类的成员.
可以看到两个test函数都报错了, 提示serializable.detail.WithoutSerializable$NonSerializable这个类无法序列化.

遇到这种情况可以用一些方法解决, 比如说在这个字段前面加上transient关键字, 然后在类中实现writeObjectreadObject方法来手动序列化这个对象, 后面会有例子.

package serializable.detail;

public class WithoutSerializable implements Serializable {

    public static class NonSerializable{

    }

    public static class Item implements Serializable{
        NonSerializable nonSerializable = new NonSerializable();
    }

    public static void testItem() throws IOException {
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("/tmp/test.obj"));
        WithoutSerializable withoutSerializable = new WithoutSerializable();
        Item item = new Item();
        // Exception in thread "main" java.io.NotSerializableException: serializable.detail.WithoutSerializable$NonSerializable
        objectOutputStream.writeObject(item);
        objectOutputStream.close();
    }


    public static void testWithoutSerializable() throws IOException {
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("/tmp/test.obj"));
        NonSerializable nonSerializable = new NonSerializable();
        // Exception in thread "main" java.io.NotSerializableException: serializable.detail.WithoutSerializable$NonSerializable
        objectOutputStream.writeObject(nonSerializable);
        objectOutputStream.close();
    }

    public static void main(String[] args) throws IOException {
        testWithoutSerializable();
//        testItem();
    }

}

结合transient, writeObject, readObject的例子

transient:
如果一个字段被标注了transient, 那么默认序列化的时候不会序列化该字段.

关于writeObject以及readObject的注释:

 * Classes that require special handling during the serialization and
 * deserialization process must implement special methods with these exact
 * signatures:
 *
 * <PRE>
 * private void writeObject(java.io.ObjectOutputStream out)
 *     throws IOException
 * private void readObject(java.io.ObjectInputStream in)
 *     throws IOException, ClassNotFoundException;
 * </PRE>
 *
 * <p>The writeObject method is responsible for writing the state of the
 * object for its particular class so that the corresponding
 * readObject method can restore it.  The default mechanism for saving
 * the Object's fields can be invoked by calling
 * out.defaultWriteObject. The method does not need to concern
 * itself with the state belonging to its superclasses or subclasses.
 * State is saved by writing the individual fields to the
 * ObjectOutputStream using the writeObject method or by using the
 * methods for primitive data types supported by DataOutput.
 *
 * <p>The readObject method is responsible for reading from the stream and
 * restoring the classes fields. It may call in.defaultReadObject to invoke
 * the default mechanism for restoring the object's non-static and
 * non-transient fields.  The defaultReadObject method uses information in
 * the stream to assign the fields of the object saved in the stream with the
 * correspondingly named fields in the current object.  This handles the case
 * when the class has evolved to add new fields. The method does not need to
 * concern itself with the state belonging to its superclasses or subclasses.
 * State is saved by writing the individual fields to the
 * ObjectOutputStream using the writeObject method or by using the
 * methods for primitive data types supported by DataOutput.

writeObject方法用于控制序列化的具体过程, readObject用于控制反序列化的具体过程.

注意反序列化的时候, 该类的构造函数是没有被调用的.

用于序列化的类:
注意passwordreadFromFile字段是被标记了transient的.

package serializable.detail;

import java.io.IOException;
import java.io.Serializable;

public class People implements Serializable {

    // 用于辨别这个类的版本, 因为可能会有新旧版本
    public static final long serialVersionUID = 0L;

    private String name;
    private int age;

    // 使用transient标记, 说明该字段不会被序列化
    private transient String password;
    private transient boolean readFromFile;

    // 无参构造器
    public People(){
        System.out.println("People()");
    }

    public People(String name, int age){
        System.out.println("People(String name, int age)");
        this.name = name;
        this.age = age;
    }

    // 不是接口方法, 序列化过程会通过反射来调用
    private void writeObject(java.io.ObjectOutputStream out) throws IOException {
        // 先调用defaultWriteObject()方法来序列化其他字段
        out.defaultWriteObject();
        out.writeBoolean(true);
    }

    // 不是接口方法, 序列化过程会通过反射来调用
    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException{
        // 先调用`defaultReadObject`来反序列化其他字段
        in.defaultReadObject();
        readFromFile = in.readBoolean();
    }



    @Override
    public String toString() {
        return String.format("[%s, %d, %s, read from file: %s]", name, age, password, readFromFile);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

测试代码:

    public static final String filename = "/tmp/test.obj";

    public static void testPeopleSerialize() throws IOException, ClassNotFoundException {
        People people = new People("xiaofu", 22);
        people.setPassword("12345");
        System.out.println("before serializing: ");
        System.out.println(people);

        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filename));
        objectOutputStream.writeObject(people);
        objectOutputStream.close();


        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(filename));
        // 可能会抛出ClassNotFoundException, 说明需要在classpath中有这个class
        People readPeople = (People) objectInputStream.readObject();
        System.out.println("after serializing:");
        System.out.println(readPeople);

        objectInputStream.close();
    }

输出:

People(String name, int age)
before serializing: 
[xiaofu, 22, 12345, read from file: false]
after serializing:
[xiaofu, 22, null, read from file: true]

可以看到password并没有被序列化, 而readFromFile是由writeObject方法序列化的.

Externalizable接口

Externalizable接口是继承于Serializable接口的. 它定义了两个方法分别用于控制序列化反序列化过程.

  • void writeExternal(ObjectOutput out) throws IOException;
  • void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;

反序列化的时候, 会调用类的无参构造函数.

实例:

package serializable.detail;

import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;

// Externalizable 继承了 Serializable
// 同时如果一个类同时implements了Externalizable和Serializable
// 那么Externalizable会被实际使用
// 而且Externalizable在反序列化过程中会调用默认构造函数来生成对象
// 而Serializable不会
public class ExternalSerialize implements Externalizable {

    private int id;
    private String name;

    public ExternalSerialize(){
        System.out.println("in default constructor");
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeInt(id);
        out.writeObject(name);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        id = in.readInt();
        name = (String) in.readObject();
    }

    @Override
    public String toString() {
        return String.format("[%d, %s]", id, name);
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

测试:

    public static void testExternalSerialize() throws IOException, ClassNotFoundException {
        ExternalSerialize externalSerialize = new ExternalSerialize();
        externalSerialize.setId(1);
        externalSerialize.setName("test");
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filename));
        objectOutputStream.writeObject(externalSerialize);
        objectOutputStream.close();


        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(filename));
        // 可能会抛出ClassNotFoundException, 说明需要在classpath中有这个class
        ExternalSerialize externalSerialize1 = (ExternalSerialize) objectInputStream.readObject();
        objectInputStream.close();

        System.out.println(externalSerialize1);

    }

输出:

in default constructor
in default constructor
[1, test]

单例的序列化

如果一个类是按照单例来实现的, 那么反序列化后会得到该类的第二个实例, 这可能不是我们想要的结果, 这个时候可以借助readResolve方法来解决.

实例:

package serializable.detail;

import java.io.IOException;
import java.io.ObjectStreamException;
import java.io.Serializable;

// 这里提到一个不需要同步的单例创建方法
// https://stackoverflow.com/questions/16106260/thread-safe-singleton-class
public class Singleton implements Serializable{

    public static final long serialVersionUID = 1L;

    private static  Singleton INSTANCE;

    private Singleton(){

    }

    public static Singleton getInstance(){

        if (INSTANCE != null)
            return INSTANCE;

        synchronized (Singleton.class) {
            if (INSTANCE == null) {
                INSTANCE = new Singleton();
            }
        }

        return INSTANCE;
    }

    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException{
        System.out.println("in readObject");
        // in.defaultReadObject();
    }

    // 会替换掉从流中生成的对象
    Object readResolve() throws ObjectStreamException {
        System.out.println("in readResolve");
        return Singleton.getInstance();
    }

}

测试:

    public static void testSingleton() throws IOException, ClassNotFoundException {
        Singleton singleton = Singleton.getInstance();

        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filename));
        objectOutputStream.writeObject(singleton);
        objectOutputStream.close();


        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(filename));
        // 可能会抛出ClassNotFoundException, 说明需要在classpath中有这个class
        Singleton singleton1 = (Singleton) objectInputStream.readObject();
        objectInputStream.close();

        System.out.println(singleton == singleton1);
    }

输出:

in readObject
in readResolve
true

可以看出反序列化的时候依然调用了readObject方法, 但是最终返回的对象是readResolve方法中返回的对象.

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容