浅克隆无法对对象中包含的其他非java原是类型数据进行复制。如果需要复制其他非java原是类型数据,则需要使用深克隆方式,对象以及其内部所有对象必须实现java.io.Serializable接口,clone方法改写成以下形式:
- public Object clone(){
- try {
- ByteArrayOutputStream ot = new ByteArrayOutputStream();
- ObjectOutputStream oo = new ObjectOutputStream(ot);
- oo.writeObject(this);
- ByteArrayInputStream it = new ByteArrayInputStream(ot.toByteArray());
- ObjectInputStream oi = new ObjectInputStream(it);
- return (oi.readObject());
- } catch (IOException e) {
- e.printStackTrace();
- return null;
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- return null;
- }
- }