内部类如何序列化
时间: 2023-08-11 18:11:18 浏览: 66
内部类的序列化过程和普通类是一样的。但是,需要注意的是,如果内部类是非静态的,则需要序列化其外部类的引用,以便在反序列化时能够正确地重建内部类实例。同时,如果内部类实现了 Serializable 接口,则需要确保其外部类也实现了 Serializable 接口,否则在序列化时会抛出 NotSerializableException 异常。
以下是一个示例代码:
```java
import java.io.*;
class Outer implements Serializable {
private static final long serialVersionUID = 1L;
private int outerValue;
public Outer(int outerValue) {
this.outerValue = outerValue;
}
public int getOuterValue() {
return outerValue;
}
public void setOuterValue(int outerValue) {
this.outerValue = outerValue;
}
class Inner implements Serializable {
private static final long serialVersionUID = 1L;
private int innerValue;
public Inner(int innerValue) {
this.innerValue = innerValue;
}
public int getInnerValue() {
return innerValue;
}
public void setInnerValue(int innerValue) {
this.innerValue = innerValue;
}
}
}
public class SerializationExample {
public static void main(String[] args) throws Exception {
Outer outer = new Outer(10);
Outer.Inner inner = outer.new Inner(20);
// 序列化
FileOutputStream fos = new FileOutputStream("data.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(outer);
oos.close();
// 反序列化
FileInputStream fis = new FileInputStream("data.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Outer outer2 = (Outer) ois.readObject();
ois.close();
// 验证序列化结果
System.out.println("Outer value: " + outer2.getOuterValue());
System.out.println("Inner value: " + outer2.new Inner(0).getInnerValue());
}
}
```
在上面的示例中,我们定义了一个包含内部类的外部类 Outer,并进行了序列化和反序列化。注意,在序列化和反序列化时,我们都需要将外部类和内部类同时序列化和反序列化。最终输出的结果如下:
```
Outer value: 10
Inner value: 20
```
这表明内部类的序列化和反序列化过程都是成功的。
相关推荐
![](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)
![](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)