Here you can find the source of deepClone(Object obj)
Parameter | Description |
---|---|
obj | must implement Serializable |
public static Object deepClone(Object obj)
//package com.java2s; //License from project: BSD License import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; public class Main { /**/*from w ww . j a v a2 s . c o m*/ * * @param obj * must implement Serializable * @return a deep copy of an object */ public static Object deepClone(Object obj) { ObjectOutputStream oos = null; ObjectInputStream ois = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); oos.writeObject(obj); oos.flush(); ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray()); ois = new ObjectInputStream(bin); return ois.readObject(); } catch (Exception e) { e.printStackTrace(); return null; } finally { close(oos); close(ois); } } public static void close(OutputStream os) { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } public static void close(InputStream is) { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } }