我突然遇到了在 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);
}
}
输出是:
com.xxx.zzz.Parent, 5
com.xxx.zzz.Child, 10,20
com.xxx.zzz.Parent, 5
com.xxx.zzz.Child, 10,20
还有另一种(更短的)方法(使用反射):
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;
}
}
无需在 Child 类中覆盖 copy()。但我不确定使用 getClass().newInstance() 构造一个副本占位符有多“合法”......
上面的解决方案值得使用还是有更常见/强大/简单的方法?
谢谢 !