← 返回首页

Java序列化:对象的持久化与传输

📂 java ⏱ 2 min 254 words

Java序列化:对象的持久化与传输

概述

序列化是将对象转换为字节流的过程,反序列化是将字节流转换为对象的过程。

1. Serializable接口

import java.io.*;

public class User implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    private transient String password;

    public User(String name, int age, String password) {
        this.name = name;
        this.age = age;
        this.password = password;
    }
}

2. 序列化与反序列化

import java.io.*;

public class SerializationDemo {
    public static void serialize(Object obj, String filename) throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(
                new FileOutputStream(filename))) {
            oos.writeObject(obj);
            System.out.println("序列化完成");
        }
    }

    public static Object deserialize(String filename)
            throws IOException, ClassNotFoundException {
        try (ObjectInputStream ois = new ObjectInputStream(
                new FileInputStream(filename))) {
            return ois.readObject();
        }
    }
}

3. Externalizable接口

import java.io.*;

public class Product implements Externalizable {
    private String name;
    private double price;
    private int quantity;

    public Product() {}

    public Product(String name, double price, int quantity) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeUTF(name);
        out.writeDouble(price);
        out.writeInt(quantity);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException {
        name = in.readUTF();
        price = in.readDouble();
        quantity = in.readInt();
    }
}

4. JSON序列化

import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonSerializationDemo {
    private static final ObjectMapper mapper = new ObjectMapper();

    public static String toJson(Object obj) throws Exception {
        return mapper.writeValueAsString(obj);
    }

    public static <T> T fromJson(String json, Class<T> clazz) throws Exception {
        return mapper.readValue(json, clazz);
    }
}

5. 序列化安全性

// 使用白名单验证
public class SafeDeserialization {
    private static final Set<String> ALLOWED_CLASSES = Set.of(
        "com.example.User", "com.example.Product"
    );
}

最佳实践

  1. 使用serialVersionUID:保证版本兼容
  2. 使用transient:排除不需要序列化的字段
  3. 优先使用JSON:更安全、更通用
  4. 验证反序列化:避免安全漏洞
  5. 性能考虑:JSON序列化性能较好

总结

序列化是对象持久化和网络传输的基础,掌握Java原生序列化和JSON序列化,可以实现对象的高效传输。