如何实现java序列化
时间: 2024-05-10 18:16:09 浏览: 12
Java序列化可以将对象转换成字节流,以便在网络上传输或保存在本地文件中。下面是一个简单的示例:
1. 首先,需要让对象实现 Serializable 接口,这个接口没有方法,只是作为一个标记接口告诉JVM这个类可以被序列化。
```java
import java.io.Serializable;
public class Person implements Serializable {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
2. 然后,可以使用 ObjectOutputStream 类将对象序列化为字节流。
```java
import java.io.*;
public class SerializeDemo {
public static void main(String[] args) {
Person person = new Person("张三", 20);
try {
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(person);
out.close();
fileOut.close();
System.out.println("对象已被序列化并保存到person.ser文件中。");
} catch (IOException i) {
i.printStackTrace();
}
}
}
```
3. 最后,可以使用 ObjectInputStream 类将字节流反序列化为对象。
```java
import java.io.*;
public class DeserializeDemo {
public static void main(String[] args) {
Person person = null;
try {
FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
person = (Person) in.readObject();
in.close();
fileIn.close();
} catch (IOException i) {
i.printStackTrace();
return;
} catch (ClassNotFoundException c) {
System.out.println("Person类未找到");
c.printStackTrace();
return;
}
System.out.println("反序列化后的对象:");
System.out.println("姓名:" + person.getName());
System.out.println("年龄:" + person.getAge());
}
}
```
这样就可以实现Java序列化了。需要注意的是,序列化和反序列化的过程中,对象的成员变量都需要是可序列化的。如果某个成员变量无法被序列化,可以使用 transient 关键字进行标记,使其不参与序列化。
相关推荐
![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_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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)