goback add

java对象克隆clone

3620 点击·0 回帖
灯火互联
楼主

/**
  * 克隆
  *
  * @param <T>
  * @param t
  * @return
  */
public static final <T> T clone(T t) {
  try {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   ObjectOutputStream out = new ObjectOutputStream(baos);
   out.writeObject(t);
   out.close();
   ByteArrayInputStream bin = new ByteArrayInputStream(baos
     .toByteArray());
   ObjectInputStream in = new ObjectInputStream(bin);
   Object clone = in.readObject();
   in.close();
   return (T) (clone);
  } catch (ClassNotFoundException e) {
   throw new internalError(e.toString());
  } catch (StreamCorruptedException e) {
   throw new InternalError(e.toString());
  } catch (IOException e) {
   throw new InternalError(e.toString());
  }
}


摘自 lpdx111的专栏


喜欢0 评分0