How to properly override clone method?

后端 未结 9 2189
时光说笑
时光说笑 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条回答
  •  醉酒成梦
    2020-11-22 12:36

    Just because java's implementation of Cloneable is broken it doesn't mean you can't create one of your own.

    If OP real purpose was to create a deep clone, i think that it is possible to create an interface like this:

    public interface Cloneable {
        public T getClone();
    }
    

    then use the prototype constructor mentioned before to implement it:

    public class AClass implements Cloneable {
        private int value;
        public AClass(int value) {
            this.vaue = value;
        }
    
        protected AClass(AClass p) {
            this(p.getValue());
        }
    
        public int getValue() {
            return value;
        }
    
        public AClass getClone() {
             return new AClass(this);
        }
    }
    

    and another class with an AClass object field:

    public class BClass implements Cloneable {
        private int value;
        private AClass a;
    
        public BClass(int value, AClass a) {
             this.value = value;
             this.a = a;
        }
    
        protected BClass(BClass p) {
            this(p.getValue(), p.getA().getClone());
        }
    
        public int getValue() {
            return value;
        }
    
        public AClass getA() {
            return a;
        }
    
        public BClass getClone() {
             return new BClass(this);
        }
    }
    

    In this way you can easely deep clone an object of class BClass without need for @SuppressWarnings or other gimmicky code.

提交回复
热议问题