序列化深度复制对象

// returns a deep copy of an object
	public static <T> T deepCopy(T oldObj) throws Exception {
		ObjectOutputStream oos = null;
		ObjectInputStream ois = null;
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			oos = new ObjectOutputStream(bos);
			
			// serialize and pass the object
			oos.writeObject(oldObj);
			oos.flush();
			ByteArrayInputStream bin = new ByteArrayInputStream(bos.toByteArray());
			ois = new ObjectInputStream(bin);
			
			// return the new object
			return (T) ois.readObject();
		} catch (Exception e) {
			throw (e);
		} finally {
			if (oos != null) oos.close();
			if (ois != null) ois.close();
		}
	}

猜你喜欢

转载自nbqwcnm.iteye.com/blog/1125172