最近项目中遇到了将实体类序列化成字符串存进数据库的需求,特地写了个公用的Object 序列化成字符串的工具类:
要求: Object 必须继承Serializable 接口 ,最好有个序列化Id 这样在类转换和扩展时 能避免很多不必要的错误。关于java类的序列化可参考:
http://www.ibm.com/developerworks/cn/java/j-lo-serial/index.html?ca=drs- 这篇文章 通俗易懂。
下面贴上代码, 大家可以顺便复习下 IO 和 泛型的知识。
代码:
public class SerializeTool
{
public static String object2String(Object obj)
{
String objBody = null;
ByteArrayOutputStream baops = null;
ObjectOutputStream oos = null;
try
{
baops = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baops);
oos.writeObject(obj);
byte[] bytes = baops.toByteArray();
objBody = new String(bytes);
} catch (IOException e)
{
LogUtil.debug(e);
} finally
{
try
{
if (oos != null)
oos.close();
if (baops != null)
baops.close();
} catch (IOException e)
{
LogUtil.debug(e);
}
}
return objBody;
}
@SuppressWarnings("unchecked")
public static <T extends Serializable> T getObjectFromString
(String objBody, Class<T> clazz)
{
byte[] bytes = objBody.getBytes();
ObjectInputStream ois = null;
T obj = null;
try
{
ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
obj = (T) ois.readObject();
} catch (IOException e)
{
LogUtil.debug(e);
} catch (ClassNotFoundException e)
{
LogUtil.debug(e);
} finally
{
try
{
if (ois != null)
ois.close();
} catch (IOException e)
{
LogUtil.debug(e);
}
}
return obj;
}
}