是的,除了返回已传递的相同引用之外,它什么也不做。
您可能正在寻找Object#clone()* 方法:
public Validation copy(Validation newValidation) {
return newValidation.clone();
}
在 95% 的情况下,这是针对不同类型任务的最合适和最合适的解决方案。如果没有必要,你不应该重新发明轮子。
正如 Java 文档所说:
...此方法执行此对象的“浅拷贝”,而不是“深拷贝”操作。
...返回之前可能需要修改super.clone返回的对象的一个或多个字段。
Validation y = x.copy(x);
您不应将x 传递给copy 方法,因为当您在x 实例上调用此方法时,您可以在类中访问this,在这种情况下,它代表你的x。
Validation y = x.clone();
对于“浅拷贝”,前面的示例很好,但是对于“深拷贝”,您需要覆盖默认的Object#clone() 行为:
class A implements Cloneable {
public @Override A clone() throws CloneNotSupportedException {
return (A)super.clone(); // or or another implementation
}
}
class Validation implements Cloneable {
// an example of a reference-type field
private A a; // with a setter
public @Override Validation clone() throws CloneNotSupportedException {
Validation newClone = new Validation();
// note that the `A` class has to implement the `Cloneable`
// and override the `clone` method making it `public`
newClone.setA(this.a.clone());
return newClone;
}
}
*不要忘记实现Cloneable 接口以允许克隆。
阅读:Effective Java, Item 11: Override clone judiciously.