Protostuff序列化和反序列化

Protostuff

Protostuff在序列化和反序列化的速度上是非常快的,在要求速度简洁快速可以使用此框架,相比protobuffer使用起来简单方便

Protostuff工具类

public class SerializationUtil {

    private static Map, Schema> cachedSchema = new ConcurrentHashMap, Schema>();

    private static Objenesis objenesis = new ObjenesisStd(true);

    private SerializationUtil() {
    }

    /**
     * 获取类的schema
     *
     * @param cls cls
     * @return Schema
     */
    @SuppressWarnings("unchecked")
    private static  Schema getSchema(Class cls) {
        Schema schema = (Schema) cachedSchema.get(cls);
        if (schema == null) {
            schema = RuntimeSchema.createFrom(cls);
            cachedSchema.put(cls, schema);
        }
        return schema;
    }

    /**
     * 序列化(对象 -> 字节数组)
     */
    @SuppressWarnings("unchecked")
    public static  byte[] serialize(T obj) {
        Class cls = (Class) obj.getClass();
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        try {
            Schema schema = getSchema(cls);
            //序列化
            return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        } finally {
            buffer.clear();
        }
    }

    /**
     * 反序列化(字节数组 -> 对象)
     */
    public static  T deserialize(byte[] data, Class cls) {
        try {
            /*
             * 如果一个类没有参数为空的构造方法时候,那么你直接调用newInstance方法试图得到一个实例对象的时候是会抛出异常的
             * 通过ObjenesisStd可以完美的避开这个问题
             * */
            //实例化
            T message = objenesis.newInstance(cls);
            //获取类的schema
            Schema schema = getSchema(cls);
            ProtostuffIOUtil.mergeFrom(data, message, schema);
            return message;
        } catch (Exception e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
}

maven依赖

        
            io.protostuff
            protostuff-core
            1.4.0
        
 
        
            io.protostuff
            protostuff-runtime
            1.4.0
        

你可能感兴趣的:(序列化)