Protostuff序列化和反序列化

Java序列化和反序列化


序列化和反序列化是在應對網(wǎng)絡編程最常遇到的問題之一。
序列化就是將Java Object轉成byte[];反序列化就是將byte[]轉成Java Object。
這里不介紹JDK serializable的序列化方式,而是介紹一個更高效的序列化庫-protostuff。

Protostuff簡介


Protostuff的項目主頁:http://www.protostuff.io/

Protostuff是一個序列化庫,支持一下序列化格式:

  • protobuf
  • protostuff(本地)
  • graph
  • json
  • smile
  • xml
  • yaml
  • kvp

序列化和反序列化工具


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

第3行:獲得對象的類;
第4行:使用LinkedBuffer分配一塊默認大小的buffer空間;
第6行:通過對象的類構建對應的schema;
第7行:使用給定的schema將對象序列化為一個byte數(shù)組,并返回。

反序列化
public static <T> T deserialize(byte[] data, Class<T> cls) {
    try {
        T message = objenesis.newInstance(cls);
        Schema<T> schema = getSchema(cls);
        ProtostuffIOUtil.mergeFrom(data, message, schema);
        return message;
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}

第3行:使用objenesis實例化一個類的對象;
第4行:通過對象的類構建對應的schema;
第5,6行:使用給定的schema將byte數(shù)組和對象合并,并返回。

構建schema

構建schema的過程可能會比較耗時,因此希望使用過的類對應的schema能被緩存起來。代碼如下,不再贅述:

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

private static <T> Schema<T> getSchema(Class<T> cls) {
    Schema<T> schema = (Schema<T>) cachedSchema.get(cls);
    if (schema == null) {
        schema = RuntimeSchema.createFrom(cls);
        if (schema != null) {
            cachedSchema.put(cls, schema);
        }
    }
    return schema;
}

可以看到方法第4行使用了RuntimeSchema,關于RuntimeSchema的用法,參考:// TODO

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容