封装通用序列化类
Posted wsjun
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了封装通用序列化类相关的知识,希望对你有一定的参考价值。
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import static com.alibaba.druid.util.JdbcUtils.close;
/**
* @author: wsj
* @date: 2018/10/10
* @time: 17:46
*/
@Slf4j
public class ListTranscoder {
public static <T> byte[] serialize(List<T> value) {
if (value == null) {
throw new NullPointerException("Can‘t serialize null");
}
byte[] rv = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
for (T user : value) {
os.writeObject(user);
}
os.writeObject(null);
os.close();
bos.close();
rv = bos.toByteArray();
} catch (IOException e) {
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
close(os);
close(bos);
}
return rv;
}
public static <T> List deserialize(byte[] in) {
List<T> list = new ArrayList<>();
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if(in != null) {
bis=new ByteArrayInputStream(in);
is=new ObjectInputStream(bis);
while (true) {
T user = (T) is.readObject();
if(user == null){
break;
}else{
list.add(user);
}
}
is.close();
bis.close();
}
} catch (IOException e) {
log.warn("Caught IOException decoding %d bytes of data",
in == null ? 0 : in.length, e);
} catch (ClassNotFoundException e) {
log.warn("Caught CNFE decoding %d bytes of data",
in == null ? 0 : in.length, e);
} finally {
close(is);
close(bis);
}
return list;
}
}
以上是关于封装通用序列化类的主要内容,如果未能解决你的问题,请参考以下文章
通用的ProtostuffSerializer for Java