java反序列化,举一个例子
时间: 2024-04-29 20:26:52 浏览: 65
Java反序列化是将二进制数据流转换为Java对象。以下是一个简单的Java反序列化例子:
假设我们有以下Java类:
```java
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
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;
}
}
```
我们可以将一个Person对象序列化为一个字节数组:
```java
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class SerializationExample {
public static void main(String[] args) throws IOException {
Person person = new Person("Alice", 25);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(person);
byte[] data = baos.toByteArray();
System.out.println("Serialized data: " + data);
}
}
```
现在我们可以将字节数组反序列化为一个Person对象:
```java
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
public class DeserializationExample {
public static void main(String[] args) throws IOException, ClassNotFoundException {
byte[] data = { -84, -19, 0, 5, 115, 114, 0, 22, 80, 101, 114, 115, 111, 110, 6, 0, 0, 0, 0, 0, 0, 0, 1, 0, 3, 97, 103, 101, -126, -14, -12, 86, 1, 0, 4, 110, 97, 109, 101, 116, 0, 5, 65, 108, 105, 99, 101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
ByteArrayInputStream bais = new ByteArrayInputStream(data);
ObjectInputStream ois = new ObjectInputStream(bais);
Person person = (Person) ois.readObject();
System.out.println("Deserialized Person: " + person.getName() + ", " + person.getAge());
}
}
```
这个例子中,我们将Person对象序列化为字节数组,然后将字节数组反序列化为一个新的Person对象。
阅读全文