封装通用序列化类



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;
}

}
posted @ 2018-10-12 14:48  wsjun  阅读(448)  评论(0编辑  收藏  举报