Java完整实现自定义序列化类,要求该类可以实现编号,姓名,年龄数据的序列化
时间: 2023-08-16 20:06:27 浏览: 53
Java提供了Serializable接口,只需实现该接口并定义相应字段即可实现自定义序列化类。下面是一个示例:
```
import java.io.*;
public class Person implements Serializable {
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 void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
// 序列化方法
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeInt(id);
out.writeObject(name);
out.writeInt(age);
}
// 反序列化方法
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
id = in.readInt();
name = (String) in.readObject();
age = in.readInt();
}
}
```
在这个示例中,我们实现了Serializable接口,并定义了三个字段:id、name和age。同时,我们还定义了writeObject和readObject方法,用于序列化和反序列化这三个字段。
在writeObject方法中,我们使用ObjectOutputStream的writeInt和writeObject方法分别将id、name和age写入输出流中。
在readObject方法中,我们使用ObjectInputStream的readInt和readObject方法分别读取id、name和age。
这样,我们就实现了一个自定义序列化类,可以序列化编号、姓名和年龄数据。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)