如何复制一个java对象
1个回答
展开全部
/**
* 复制对象
*
* @param srcObj
* @return
*/
public static Object depthClone(Object srcObj) {
if (srcObj == null) {
return null;
}
Object cloneObj = null;
ByteArrayOutputStream out = null;
ObjectOutputStream oo = null;
ByteArrayInputStream in = null;
ObjectInputStream oi = null;
try {
out = new ByteArrayOutputStream();
oo = new ObjectOutputStream(out);
oo.writeObject(srcObj);
in = new ByteArrayInputStream(out.toByteArray());
oi = new ObjectInputStream(in);
cloneObj = oi.readObject();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (oo != null) {
try {
oo.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (in != null) {
try {
in.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
if (oi != null) {
try {
oi.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
return cloneObj;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询