Java cloning abstract objects

后端 未结 4 1031
执笔经年
执笔经年 2020-12-16 15:37

I\'m wondering if there is any way to do the following. I have an abstract class, Shape, and all its different subclasses and I want to override the clone metho

4条回答
  •  庸人自扰
    2020-12-16 15:46

    You can resolve with reflection:

    public abstract class Shape {
    
        private String str;
    
        public Shape()  {
    
        }
    
        protected Shape(String str) {
            this.str = str;
        }
    
        public Shape clone() throws CloneNotSupportedException
        {
            try {
                return (Shape)getClass().getDeclaredConstructor(String.class).newInstance(this.toString());
            } catch (Exception e) {
                throw new CloneNotSupportedException();
            }
        }
    
        public String toString() {
            return "shape";
        }
    
    public class Round extends Shape
    {
        public Round()
        {
            super();
        }
        protected Round(String str) {
            super(str);
        }
    
        @Override
        public String toString() {
            return "round";
        }
    }
    
    main(){
      Shape round = new Round();        
      Shape clone = round.clone();
      System.out.println(round);
      System.out.println(clone);
    }
    

    but - IMO - is a poor implementation and error-prone with a lot of pits; the best use of Cloneable and Object.clone() is to not use them! You have a lot of way to do the same thing (like serialization for deep-clone) and shallow-clone that allow your a better control of flow.

提交回复
热议问题