import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.logging.Level; import java.util.logging.Logger; import bruce.lib.swing.JTextBox; public class CloneObject { public static Object clone(Object source) { Object newObject = new Object(); ObjectOutputStream ooStr = null; try { ByteArrayOutputStream baoStr = new ByteArrayOutputStream(); ooStr = new ObjectOutputStream(baoStr); ooStr.writeObject(source); ooStr.flush(); ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baoStr.toByteArray())); newObject = in.readObject(); } catch (ClassNotFoundException ex) { Logger.getLogger(CloneObject.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(CloneObject.class.getName()).log(Level.SEVERE, null, ex); } finally { try { ooStr.close(); } catch (IOException ex) { Logger.getLogger(CloneObject.class.getName()).log(Level.SEVERE, null, ex); } } return newObject; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub JTextBox textbox = new JTextBox("A simple textbox", 20); System.out.printf("Hashcode : %d%n", textbox.hashCode()); JTextBox clonedTextBox = (JTextBox) clone(textbox); System.out.printf("Cloned hashcode : %d%n", clonedTextBox.hashCode()); System.out.printf("Cloned text : %s%n", clonedTextBox.getText()); } }