浏览 494
                         扫码
                        
                    
                    
                    在Java中,序列化(Serialization)是将对象转换为字节流的过程,而反序列化(Deserialization)是将字节流转换为对象的过程。序列化与反序列化主要用于对象的持久化存储或对象在网络中的传输。
序列化(Serialization)
- 首先,需要让类实现
Serializable接口,这是一个标记接口,没有任何方法需要实现。 
import java.io.Serializable;
public class Person implements Serializable {
    private String name;
    private int age;
    
    // Constructors, getters and setters
}
- 使用
ObjectOutputStream类来实现序列化,将对象写入输出流中。 
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class SerializationExample {
    public static void main(String[] args) {
        Person person = new Person("Alice", 30);
        
        try (FileOutputStream fileOut = new FileOutputStream("person.ser");
             ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
            out.writeObject(person);
            System.out.println("Object has been serialized");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
反序列化(Deserialization)
- 使用
ObjectInputStream类来实现反序列化,从输入流中读取对象。 
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class DeserializationExample {
    public static void main(String[] args) {
        try (FileInputStream fileIn = new FileInputStream("person.ser");
             ObjectInputStream in = new ObjectInputStream(fileIn)) {
            Person person = (Person) in.readObject();
            System.out.println("Object has been deserialized");
            System.out.println("Name: " + person.getName());
            System.out.println("Age: " + person.getAge());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
注意事项
- 序列化和反序列化的类必须在同一个包中。
 - 序列化版本号可以通过在类中增加
private static final long serialVersionUID进行控制。 - 注意序列化和反序列化可能会引发
InvalidClassException异常,所以在进行序列化和反序列化时要谨慎处理版本兼容性问题。 
以上是序列化与反序列化的基础教程,希望能帮助你了解如何在Java中进行对象的持久化存储与传输。
