通常在采访中会询问您如何创建可序列化的界面。问题出现了,如果我们尝试检查可序列化的API,它不包括任何方法,因为它是标记接口,如果我们尝试在用户定义的接口中覆盖相同的功能。如果类而不是实现serialzable接口创建自己的可序列化接口,它会实现吗?如何实现相同的可序列化功能?它将如何序列化对象或持久化对象的状态?
答案 0 :(得分:0)
通过实现readObject()和writeObject()方法创建自定义序列化。此行为将覆盖默认的序列化行为。
示例: 公共类用户实现Serializable {
private static final long serialVersionUID = 7829136421241571165L;
private String firstName;
private String lastName;
private int accountNumber;
private Date dateOpened;
public User(String firstName, String lastName, int accountNumber, Date dateOpened) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.accountNumber = accountNumber;
this.dateOpened = dateOpened;
}
public User() {
super();
}
//Setters and Getters
private void readObject(ObjectInputStream aInputStream) throws ClassNotFoundException, IOException
{
firstName = aInputStream.readUTF();
lastName = aInputStream.readUTF();
accountNumber = aInputStream.readInt();
dateOpened = new Date(aInputStream.readLong());
}
private void writeObject(ObjectOutputStream aOutputStream) throws IOException
{
aOutputStream.writeUTF(firstName);
aOutputStream.writeUTF(lastName);
aOutputStream.writeInt(accountNumber);
aOutputStream.writeLong(dateOpened.getTime());
}
}