Java cloning abstract objects

后端 未结 4 1032
执笔经年
执笔经年 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:49

    Although I doubt it is a good idea, you could use reflection:

    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    
    public class Test {
    
        public static void main(String[] args) {        
            Square s1 = new Square("test");
            Square s2 = (Square) s1.clone();
    
            // show that s2 contains the same data  
            System.out.println(s2);
            // show that s1 and s2 are really different objects
            System.out.println(s1 == s2);
        }
    
        public static abstract class Shape {
            private String str;
    
            public Shape(String str) {
                this.str = str;
            }
    
            public Shape clone() {          
                try {
                    Class cl = this.getClass();
                    Constructor cons = cl.getConstructor(String.class);
                    return (Shape) cons.newInstance(this.toString());           
                } catch (NoSuchMethodException | SecurityException |
                         InstantiationException | IllegalAccessException |
                         IllegalArgumentException | InvocationTargetException e) {  
                    e.printStackTrace();
                }           
    
                return null;
            }
    
            @Override
            public String toString() {
                return str;
            }
        }
    
        public static class Square extends Shape {
            public Square(String str) {
                super(str);
            }
        }   
    }
    

提交回复
热议问题