【序列化工具类】 SerializationUtils

用于处理对象序列化,提供比一般 Java 序列化更高级的处理能力

 

这里使用的是:3.9 的版本,还是比较新的

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
     <version>3.9</version>
</dependency>

 

<T extends Serializable> T clone(final T object)  使用序列化深度克隆

QcTemplateData qcTemplateData = new QcTemplateData();
qcTemplateData.setToken("123");
List<QcTemplateItem> list = new ArrayList<>();
qcTemplateData.setQcTemplateItems(list);
QcTemplateData clone = SerializationUtils.clone(qcTemplateData);
QcTemplateItem qcTemplateItem = new QcTemplateItem();
qcTemplateItem.setCreatedBy("hy");
list.add(qcTemplateItem);
System.out.println(JSON.toJSONString(clone));
// {"page":1,"qcTemplateItems":[],"rows":20,"start":0,"token":"123"}

 

<T extends Serializable> T roundtrip(final T msg)  序列化后,在反序列化给定的对象,非常适合测试实现的对象

 

void serialize(final Serializable obj, final OutputStream outputStream) 将对象序列化到指定的流

byte[] serialize(final Serializable obj) 将对象序列化为字节数组

HashMap<String, Object> iMap = new HashMap<>();
iMap.put("FOO", "123");
iMap.put("BAR", 456);
ByteArrayOutputStream streamTest = new ByteArrayOutputStream();
SerializationUtils.serialize(iMap, streamTest);
byte[] testBytes = streamTest.toByteArray();
System.out.println(new String(testBytes));

 

<T> T deserialize(final InputStream inputStream) 从指定流中反序列化成对象

<T> T deserialize(final byte[] objectData) 将字节数组反序列化为对象

ByteArrayInputStream inTest = new ByteArrayInputStream(testBytes);
Object test = SerializationUtils.deserialize(inTest);

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章