实现Externalnalizable接口
实现Externalnalizable接口
package meng.springboot.demo.obj;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Date;
/**
* 实现Externalizable接口的类,必须有public的无参构造器,因为在这种序列化机制中,需要构造器参与。
*
* @author mengzhang6
* @date 2018/10/22 9:45
*/
public class User3 implements Externalizable {
private int id;
private String name;
private Date addDate;
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 Date getAddDate() {
return addDate;
}
public void setAddDate(Date addDate) {
this.addDate = addDate;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", addDate=" + addDate +
'}';
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
System.out.println("Externalnalizable序列化");
out.writeObject(id);
out.writeObject(name);
out.writeObject(addDate);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
System.out.println("Externalnalizable反序列化");
id = (int) in.readObject();
name = (String) in.readObject();
addDate = (Date) in.readObject();
}
}
单元测试
@Test
public void writeObject3() throws IOException {
User3 user = new User3();
user.setId(1003);
user.setName("小猫");
user.setAddDate(Calendar.getInstance().getTime());
OutputStream outputStream = new FileOutputStream(new File("User3.out"));
ObjectOutputStream oos = new ObjectOutputStream(outputStream);
oos.writeObject(user);
}
@Test
public void readObject3() throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("User3.out"));
User3 user = (User3) ois.readObject();
System.out.println(user);
}