Serializable 和 Externalizable区别?

Serializable接口

java.io.Serializable 接口没有方法或字段,仅用于标识可序列化的语义。

public interface Serializable {
}

在进行序列化操作时,会判断要被序列化的类是否是EnumArraySerializable类型,如果都不是则直接抛出NotSerializableException

@Data
public class A1_User implements Serializable {
    private String name;
    private int age;
}
A1_User user = new A1_User();
user.setName("xiaoming");
user.setAge(18);
 
序列化
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("tempFile"));
oos.writeObject(user);

反序列化
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("tempFile")));
A1_User newUser = (A1_User) ois.readObject();

Externalizable接口

public interface Externalizable extends java.io.Serializable {
    void writeExternal(ObjectOutput out) throws IOException;
    void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
}

需要重写writeExternal()与readExternal()方法。否则所有变量的值都会变成默认值。
重写就会很灵活,可以随意加减属性

@Data
public class B1_User implements Externalizable {
    private String name;
    private int age;

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

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        name = (String) in.readObject();
        age = in.readInt();
    }
}
B1_User user = new B1_User();
user.setName("xiaoming");
user.setAge(18);

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("tempFile"));
oos.writeObject(user);

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("tempFile")));
B1_User newUser = (B1_User) ois.readObject();

两种序列化的对比

实现Serializable接口实现Externalizable接口
所有属性自动都会被序列化,简单但死板需要重写writeExternal()与readExternal()方法,啰嗦但灵活
性能略差性能略好
必须要提供一个public的无参的构造器
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值