疯狂java


您现在的位置: 疯狂软件 >> 新闻资讯 >> 正文

Java使用序列化实现深克隆


 

         序列化实现深克隆

  public static Object deepClone(Object source) {

  ObjectOutputStream oos = null;

  ObjectInputStream ois = null;

  File file = null;

  try {

  FileOutputStream fos = new FileOutputStream("objFile");

  oos = new ObjectOutputStream(fos);

  oos.writeObject(source);

  FileInputStream fis = new FileInputStream("objFile");

  ois = new ObjectInputStream(fis);

  return ois.readObject();

  } catch (Exception e) {

  System.err.println("对象克隆失败");

  e.printStackTrace();

  return null;

  } finally {

  try {

  if(null != oos) {

  oos.close();

  }

  if(null != ois) {

  ois.close();

  }

  file = new File("objFile");

  if(null != file) {

  file.delete();

  }

  } catch (IOException e) {

  e.printStackTrace();

  }

  }

  }