[Java工具] 序列化工具

简介: 依赖 com.dyuproject.protostuff protostuff-core 1.0.8 com.dyuproject.
依赖
<dependency>
    <groupId>com.dyuproject.protostuff</groupId>
    <artifactId>protostuff-core</artifactId>
    <version>1.0.8</version>
</dependency>
<dependency>
    <groupId>com.dyuproject.protostuff</groupId>
    <artifactId>protostuff-runtime</artifactId>
    <version>1.0.8</version>
</dependency>
工具类
package com.yingjun.ssm.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

/**
 * 序列化工具
 * 使用 Protostuff 开源库
 * @注意 1. 被序列化的对象的内部字段不可改变(新增,减少,改名等),否则会出现问题
 *        2. 未测试在序列化附带嵌套对象的对象时是否会出现问题
 * @autho https://github.com/wosyingjun/beauty_ssm
 */
public class ProtoStuffSerializerUtil {

    /**
     * 序列化对象
     * @param obj
     * @return
     */
    public static <T> byte[] serialize(T obj) {
        if (obj == null) {
            throw new RuntimeException("序列化对象(" + obj + ")!");
        }
        @SuppressWarnings("unchecked")
        Schema<T> schema = (Schema<T>) RuntimeSchema.getSchema(obj.getClass());
        LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
        byte[] protostuff = null;
        try {
            protostuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw new RuntimeException("序列化(" + obj.getClass() + ")对象(" + obj + ")发生异常!", e);
        } finally {
            buffer.clear();
        }
        return protostuff;
    }

    /**
     * 反序列化对象
     * @param paramArrayOfByte
     * @param targetClass
     * @return
     */
    public static <T> T deserialize(byte[] paramArrayOfByte, Class<T> targetClass) {
        if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
            throw new RuntimeException("反序列化对象发生异常,byte序列为空!");
        }
        T instance = null;
        try {
            instance = targetClass.newInstance();//依据class建立新实例
        } catch (InstantiationException | IllegalAccessException e) {
            throw new RuntimeException("反序列化过程中依据类型创建对象失败!", e);
        }
        //RuntimeSchema.getSchema()方法线程安全且自带缓存
        Schema<T> schema = RuntimeSchema.getSchema(targetClass);
        ProtostuffIOUtil.mergeFrom(paramArrayOfByte, instance, schema);
        return instance;
    }

    /**
     * 序列化列表
     * @param objList
     * @return
     */
    public static <T> byte[] serializeList(List<T> objList) {
        if (objList == null || objList.isEmpty()) {
            throw new RuntimeException("序列化对象列表(" + objList + ")参数异常!");
        }
        @SuppressWarnings("unchecked")
        Schema<T> schema = (Schema<T>) RuntimeSchema.getSchema(objList.get(0).getClass());
        LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
        byte[] protostuff = null;
        ByteArrayOutputStream bos = null;
        try {
            bos = new ByteArrayOutputStream();
            ProtostuffIOUtil.writeListTo(bos, objList, schema, buffer);
            protostuff = bos.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("序列化对象列表(" + objList + ")发生异常!", e);
        } finally {
            buffer.clear();
            try {
                if (bos != null) {
                    bos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return protostuff;
    }

    /**
     * 反序列化列表
     * @param paramArrayOfByte
     * @param targetClass
     * @return
     */
    public static <T> List<T> deserializeList(byte[] paramArrayOfByte, Class<T> targetClass) {
        if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
            throw new RuntimeException("反序列化对象发生异常,byte序列为空!");
        }

        Schema<T> schema = RuntimeSchema.getSchema(targetClass);
        List<T> result = null;
        try {
            result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(paramArrayOfByte), schema);
        } catch (IOException e) {
            throw new RuntimeException("反序列化对象列表发生异常!", e);
        }
        return result;
    }

}
待解决
  • 被序列化的对象的内部字段不可改变(新增,减少,改名等),否则会出现问题
  • 未测试在序列化附带嵌套对象的对象时是否会出现问题
参考&来源

优雅的SSM(Spring+SpringMVC+Mybatis)框架
Protostuff序列化和反序列化

相关文章
|
1月前
|
存储 Java 数据库
|
1月前
|
Java
java中日期处理的一些工具方法
java中日期处理的一些工具方法
17 1
|
11天前
|
存储 Java
Java输入输出:解释一下序列化和反序列化。
Java中的序列化和反序列化是将对象转换为字节流和反之的过程。ObjectOutputStream用于序列化,ObjectInputStream则用于反序列化。示例展示了如何创建一个实现Serializable接口的Person类,并将其序列化到文件,然后从文件反序列化回Person对象。
18 5
|
1月前
|
安全 Java 数据安全/隐私保护
提升 Java 编程安全性 - 代码加密混淆工具的重要性和应用
提升 Java 编程安全性 - 代码加密混淆工具的重要性和应用
|
1月前
|
安全 Java 数据安全/隐私保护
探讨 Java 代码混淆加固工具
探讨 Java 代码混淆加固工具
|
1月前
|
存储 安全 Java
基于Java的qq截图工具(毕业设计含源码)
基于Java的qq截图工具(毕业设计含源码)
28 0
|
1月前
|
监控 NoSQL Java
性能工具之 Java 调试工具 JDB
【2月更文挑战第25天】性能工具之 Java 调试工具 JDB
43 4
|
1月前
|
Cloud Native Java 开发者
Spring Boot 4.0:构建云原生Java应用的前沿工具
Spring Boot 4.0:构建云原生Java应用的前沿工具
|
1月前
|
存储 缓存 JSON
什么是Java序列化,它有哪些重要性
什么是Java序列化,它有哪些重要性