【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
以下是我平时项目中经常用到的对象序列化工具类
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ClassName: SerializationUtils
* @Description: 对象序列化工具类
* @author JornTang
* @date 2017年7月22日
*/
public class SerializationUtil{
private static Logger log = LoggerFactory.getLogger(SerializationUtil.class);
public SerializationUtil()
{
}
/**
* @Description: 序列化对象
* @param state
* @return
* @return byte[]
* @throws
* @author JornTang
* @date 2017年7月22日
*/
public static byte[] serialize(Object state)
{
ObjectOutputStream oos = null;
byte abyte[];
try
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(bos);
oos.writeObject(state);
oos.flush();
abyte = bos.toByteArray();
}
catch(IOException e)
{
throw new IllegalArgumentException(e);
}
if(oos != null)
try
{
oos.close();
}
catch(IOException ioexception) { }
return abyte;
}
/**
* @Description: 反序列化对象
* @param byteArray
* @return
* @return Object
* @throws
* @author JornTang
* @date 2017年7月22日
*/
public static Object deserialize(byte byteArray[])
{
ObjectInputStream oip = null;
Object obj;
try
{
oip = new ObjectInputStream(new ByteArrayInputStream(byteArray));
Object result = oip.readObject();
obj = result;
}
catch(IOException e)
{
throw new IllegalArgumentException(e);
}
catch(ClassNotFoundException e)
{
throw new IllegalArgumentException(e);
}
if(oip != null)
try
{
oip.close();
}
catch(IOException ioexception) { }
return obj;
}
/**
* @Description: 重载反序列化对象
* @param byteArray
* @return
* @return Object
* @throws
* @author JornTang
* @date 2017年7月22日
*/
public static <T> T deserialize(byte[] in, Class<T>...requiredType) {
Object rv = null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
rv = is.readObject();
}
} catch (Exception e) {
log.error("serialize error ", e);
} finally {
close(is);
close(bis);
}
return (T) rv;
}
private static void close(Closeable closeable) {
if (closeable != null)
try {
closeable.close();
} catch (IOException e) {
log.error("close stream error", e);
}
}
}
作者:[云软科技-档案管理系统](http://www.gzyrkj.net) JornTang (微信同号)
本篇文章由一文多发平台ArtiPub自动发布
来源:oschina
链接:https://my.oschina.net/u/3646522/blog/3142100