How to properly override clone method?

后端 未结 9 2258
时光说笑
时光说笑 2020-11-22 12:06

I need to implement a deep clone in one of my objects which has no superclass.

What is the best way to handle the checked CloneNotSupportedException thr

9条回答
  •  萌比男神i
    2020-11-22 12:53

    public class MyObject implements Cloneable, Serializable{   
    
        @Override
        @SuppressWarnings(value = "unchecked")
        protected MyObject clone(){
            ObjectOutputStream oos = null;
            ObjectInputStream ois = null;
            try {
                ByteArrayOutputStream bOs = new ByteArrayOutputStream();
                oos = new ObjectOutputStream(bOs);
                oos.writeObject(this);
                ois = new ObjectInputStream(new ByteArrayInputStream(bOs.toByteArray()));
                return  (MyObject)ois.readObject();
    
            } catch (Exception e) {
                //Some seriouse error :< //
                return null;
            }finally {
                if (oos != null)
                    try {
                        oos.close();
                    } catch (IOException e) {
    
                    }
                if (ois != null)
                    try {
                        ois.close();
                    } catch (IOException e) {
    
                    }
            }
        }
    }
    

提交回复
热议问题