Clone an Object with Java

On March 29, 2013, in Java, Programming, by LuCuS

Clone an object with Java.

	public static Object clone(Serializable obj) {   
		try {
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(obj);
			ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
			ObjectInputStream ois = new ObjectInputStream(bais);
			return ois.readObject();
		} catch (IOException e) {
			return null;
		} catch (ClassNotFoundException e) {
			return null;
		} 
	}

And to test it…

	public static void main(String[] args) {
		MyObject myObject1 = new MyObject();
		MyObject myObject2 = (MyObject)clone(myObject1);
	}

Thank you for your interest in my site. If you find the information provided on this site useful, please consider making a donation to help continue development!

PayPal will open in a new tab.
$2.00
$5.00
Other

Related Posts

Tagged with:  

Leave a Reply