ProtostuffSerializer

 

package com.baize.ftp.ferry.transport;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
public class ProtostuffSerializer {
    // 序列化方法
    public static <T> byte[] serialize(T obj, Class<T> clazz) {
        // 创建 Buffer
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            // 使用 Protostuff 序列化对象
            Schema<T> schema = RuntimeSchema.getSchema(clazz);
            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw new RuntimeException("序列化失败", e);
        } finally {
            buffer.clear();
        }
    }

    // 反序列化方法
    public static <T> T deserialize(byte[] data, Class<T> cls) {
        try {
            T obj = cls.newInstance();
            // 使用 Protostuff 反序列化对象
            ProtostuffIOUtil.mergeFrom(data, obj, RuntimeSchema.getSchema(cls));
            return obj;
        } catch (Exception e) {
            throw new RuntimeException("反序列化失败", e);
        }
    }
}

 

package com.baize.ftp.ferry.transport;

import java.io.Serializable;

public class User implements Serializable {
    private static final long serialVersionUID = 1L;

    private String name;
    private int age;

    public User() {} // 默认构造函数
    
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Getter 和 Setter 方法
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

 

 

package com.baize.ftp.ferry.transport;

public class Main {
    public static void main(String[] args) {
        User user = new User("Alice", 30);

        // 进行序列化
        byte[] serializedUser = ProtostuffSerializer.serialize(user, User.class);
        System.out.println("序列化成功: " + serializedUser);
        user = new User("Alice", 40);
        serializedUser = ProtostuffSerializer.serialize(user, User.class);
        System.out.println("序列化成功: " + serializedUser);

        // 进行反序列化
        User deserializedUser = ProtostuffSerializer.deserialize(serializedUser, User.class);
        System.out.println("反序列化成功: " + deserializedUser.getName() + ", " + deserializedUser.getAge());
    }
}

 

posted @ 2025-06-01 21:26  牧之丨  阅读(25)  评论(0)    收藏  举报