我有一个需要在 Java 中复制的对象。我需要在不更改原始对象本身的情况下创建一个副本并对其运行一些测试。
我假设我需要使用 clone() 方法,但这是受保护的。在网上做了一些研究后,我可以看到这可以用我班级中的公共方法覆盖。但我找不到如何做到这一点的解释。怎么可能做到这一点?
另外,这是实现我需要的最佳方式吗?
使用 Copy Constructor 的另一种选择(来自Java Practices):
public final class Galaxy {
public Galaxy (double aMass, String aName) {
fMass = aMass;
fName = aName;
}
/**
* Copy constructor.
*/
public Galaxy(Galaxy aGalaxy) {
this(aGalaxy.getMass(), aGalaxy.getName());
//no defensive copies are created here, since
//there are no mutable object fields (String is immutable)
}
/**
* Alternative style for a copy constructor, using a static newInstance
* method.
*/
public static Galaxy newInstance(Galaxy aGalaxy) {
return new Galaxy(aGalaxy.getMass(), aGalaxy.getName());
}
public double getMass() {
return fMass;
}
/**
* This is the only method which changes the state of a Galaxy
* object. If this method were removed, then a copy constructor
* would not be provided either, since immutable objects do not
* need a copy constructor.
*/
public void setMass( double aMass ){
fMass = aMass;
}
public String getName() {
return fName;
}
// PRIVATE /////
private double fMass;
private final String fName;
/**
* Test harness.
*/
public static void main (String... aArguments){
Galaxy m101 = new Galaxy(15.0, "M101");
Galaxy m101CopyOne = new Galaxy(m101);
m101CopyOne.setMass(25.0);
System.out.println("M101 mass: " + m101.getMass());
System.out.println("M101Copy mass: " + m101CopyOne.getMass());
Galaxy m101CopyTwo = Galaxy.newInstance(m101);
m101CopyTwo.setMass(35.0);
System.out.println("M101 mass: " + m101.getMass());
System.out.println("M101CopyTwo mass: " + m101CopyTwo.getMass());
}
}
有两种流行的方法。一个是提供clone
您提到的方法,就像这样。
public class C implements Cloneable {
@Override public C clone() {
try {
final C result = (C) super.clone();
// copy fields that need to be copied here!
return result;
} catch (final CloneNotSupportedException ex) {
throw new AssertionError();
}
}
注意“复制字段……这里!” 部分。初始result
只是一个浅拷贝,这意味着如果有对一个对象的引用,那么原始对象和result
将共享同一个对象。例如,如果C
包含private int[] data
您可能想要复制它。
...
final C result = (C) super.clone();
result.data = data.clone();
return result;
...
请注意,您不需要复制原始字段,因为它们的内容已经被复制,或者不可变对象,因为它们无论如何都无法更改。
第二种方法是提供一个复制构造函数。
public class C {
public C(final C c) {
// initialize this with c
}
}
或者复制工厂。
public class C {
public static C newInstance(final C c) {
return new C(c);
}
private C(final C c) {
// initialize this with c
}
}
两种方法都有各自的属性。 clone
很好,因为它是一种方法,因此您不必知道确切的类型。最后,你应该总是得到一个“完美”的副本。复制构造函数很好,因为调用者有机会做出决定,正如 Java 集合所见。
final List c = ...
// Got c from somewhere else, could be anything.
// Maybe too slow for what we're trying to do?
final List myC = new ArrayList(c);
// myC is an ArrayList, with known properties
我建议选择任何一种方法,哪种方法更适合您。
我只会在单元测试中使用其他方法,例如反射复制或立即序列化/反序列化。对我来说,他们觉得不太适合生产代码,主要是因为性能问题。
一些选项:
Cloneable
为您的对象实现并将clone()
方法设为公共。在此处查看完整说明:http: //www.cafeaulait.org/course/week4/46.htmlSerializable
为对象及其所有字段实现接口。XStream
通过 XML 执行序列化 - 您不必在这里实现任何东西。对于测试代码,序列化可能是最安全的答案,特别是如果对象已经是可序列化的,请尝试使用 Apache Commons SerializationUtils 来实现。
您可以使用 org.apache.commons.lang3.SerializationUtils 类进行对象克隆, - 类应实现 Serializable 接口。
Google App Engine 实例也支持 SerializationUtils.clone
Joshua Bloch对 cloneable 有一些有趣的说法。根据对象的大小/构造,我会向对象添加一个复制构造函数,或者使用上述解决方案之一进行序列化/反序列化。
有多种方法可以在 java 中复制对象(浅或深)。
这个答案会帮助你。