您现在的位置是:首页 > 文章详情

Protostuff 的Java序列化和反序列化

日期:2018-06-05点击:472
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_34173549/article/details/80589509
<dependency>  <groupId>io.protostuff</groupId>  <artifactId>protostuff-core</artifactId>  <version>1.4.0</version> </dependency>  <dependency>  <groupId>io.protostuff</groupId>  <artifactId>protostuff-runtime</artifactId>  <version>1.4.0</version> </dependency>
import java.util.Map;  import io.protostuff.LinkedBuffer; import io.protostuff.ProtostuffIOUtil; import io.protostuff.Schema; import io.protostuff.runtime.RuntimeSchema; /**  * @author rainyday  * @createTime 2018/6/5.  */ public class SerializationUtil { 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;  } @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();  } } public static <T> T deserialize(byte[] data, Class<T> cls) { try { T obj = cls.newInstance();  Schema<T> schema = getSchema(cls);  ProtostuffIOUtil.mergeFrom(data, obj, schema);  return obj;  } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e);  } } } 
原文链接:https://yq.aliyun.com/articles/653066
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章