天天看點

為克隆使用序列化

序列化機制為對象克隆提供了便捷方式,隻要對應的類序列化即可。序列化克隆是深度克隆。
           
class SerialCloneable implementsCloneable, Serializable{
		public Object clone(){
			try{
				ByteArrayOutputStream bout = new ByteArrayOutputStream();
				ObjectOutputStream out = new ObjectOutputStream(bout);
				out.writeObject(this);
				out.close();
	
				ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
				ObjectInputStream in = new ObjectInputStream(bin);
				Object object = in.readObject();
				in.close();
				
				return object;
			}catch(Exception e){
				return null;
			}
		}
	}