Java完整实现自定义序列化类,要求该类可以实现编号,姓名,年龄的的序列化
时间: 2023-08-16 16:05:54 浏览: 42
实现自定义序列化需要实现Serializable接口并重写writeObject()和readObject()方法,具体实现如下:
```java
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private int age;
public Person(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.writeInt(id);
out.writeObject(name);
out.writeInt(age);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
id = in.readInt();
name = (String) in.readObject();
age = in.readInt();
}
}
```
在writeObject()方法中,我们首先调用了defaultWriteObject()方法,将id、name和age字段按照默认方式序列化。然后,我们使用ObjectOutputStream的writeInt()和writeObject()方法将id、name和age字段逐个序列化。
在readObject()方法中,我们首先调用了defaultReadObject()方法,将id、name和age字段按照默认方式反序列化。然后,我们使用ObjectInputStream的readInt()和readObject()方法将id、name和age字段逐个反序列化。
这样就完成了自定义的序列化和反序列化。可以测试一下:
```java
import java.io.*;
public class Test {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person = new Person(1, "John", 30);
// 序列化
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.obj"));
out.writeObject(person);
out.close();
// 反序列化
ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.obj"));
Person p = (Person) in.readObject();
in.close();
System.out.println(p.getId() + " " + p.getName() + " " + p.getAge());
}
}
```
输出结果为:
```
1 John 30
```