对Serializable vs Externalizable感到困惑

时间:2017-07-08 19:30:44

标签: java serializable

我对在java中使用Externalizable over Serializable的优势感到困惑。特别是如果我采用以下Person类的示例。

第一个示例使用Serializable接口

public class Person implements Serializable {

private static final long serialVersionUID = 1L;
private String name;
private int age;

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

public String getName() {
    return name;
}

public int getAge() {
    return age;
}

private void writeObject(ObjectOutputStream out) throws IOException {
    out.writeObject(name);
    out.writeInt(age);  
}

private void readObject(ObjectInputStream in) throws ClassNotFoundException, 
 IOException {
    name = (String) in.readObject();
    age = in.readInt();
}
}

第二个示例使用Externalizable接口

public class Person implements Externalizable{

    private static final long serialVersionUID = 1L;

    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public int getAge() {
        return 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();

    }
}

根据理论,我们应尽可能使用Externalizable。但考虑到上面的例子,使用Externalizable接口比Serializable有什么好处?或者两种方法都一样?

就上述代码而言,使用Externalizable over Serializable会有什么不同吗?

0 个答案:

没有答案