Java中的多态副本

use*_*786 5 java reflection polymorphism deep-copy

我突然遇到了在Java中制作深度多态副本的问题.实现Clonable解决了我的问题,但它通常被称为"坏"技术.

所以,我试图找到一个"不可克隆"的解决方案:

public class Parent {
    int x;

    public Parent() {}

    public Parent(int x0) {
        x = x0;
    }

    public Parent copy() {
        Parent b = new Parent();
        b.assign(this);

        return b;
    }

    protected void assign(Parent c) {
        x = c.x;
    }

    @Override
    public String toString() {
        return getClass().getName() + ", " + x;
    }
}

public class Child extends Parent {
    int y;

    protected Child() {}

    public Child(int x0, int y0) {
        super(x0);
        y = y0;
    }

    @Override
    public Child copy() {
        Child b = new Child();
        b.assign(this);

        return b;
    }

    @Override
    protected void assign(Child c) {
        super.assign(c);
        y = c.y;
    }

    @Override
    public String toString() {
        return getClass().getName() + ", " + x + "," + y;
    }
}

public class Test {
    public static void main(String[] args) {
        Parent x = new Parent(5);
        Child y = new Child(10, 20);
        Parent z = x.copy();
        Parent w = y.copy();

        System.out.println(x);
        System.out.println(y);
        System.out.println(z);
        System.out.println(w);
    }
}
Run Code Online (Sandbox Code Playgroud)

输出是:

com.xxx.zzz.Parent, 5
com.xxx.zzz.Child, 10,20
com.xxx.zzz.Parent, 5
com.xxx.zzz.Child, 10,20
Run Code Online (Sandbox Code Playgroud)

另一种(更短的)做同样的方法(使用Reflection):

public class Parent {
    int x;

    public Parent() {}

    public Parent(int x0) {
        x = x0;
    }

    public Parent copy() {
        try {
            Parent b = getClass().newInstance();
            b.assign(this);
            return b;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
            return null;
        }
    }

    protected void assign(Parent c) {
        x = c.x;
    }

    @Override
    public String toString() {
        return getClass().getName() + ", " + x;
    }
}

public class Child extends Parent {
    int y;

    protected Child() {}

    public Child(int x0, int y0) {
        super(x0);
        y = y0;
    }

    protected void assign(Child c) {
        super.assign(c);
        y = c.y;
    }

    @Override
    public String toString() {
        return getClass().getName() + ", " + x + "," + y;
    }
}
Run Code Online (Sandbox Code Playgroud)

不需要覆盖Child类中的copy().但我不确定使用getClass().newInstance()来构造一个复制占位符是多么"合法"......

上述解决方案是值得使用还是有更常见/强大/简单的方法?

谢谢 !

vce*_*ick 0

作为使用复制构造函数或可克隆的替代方法,您可以使用序列化来执行复制。

http://www.javaworld.com/javaworld/javatips/jw-javatip76.html?page=2