다음은 Apache Commons Lang의 SerializationUtils를 사용한 자바 클론하는 예제이다.
public class SerializationUtilsTests {
@Test
public void testClone() {
B b = new B("b1", "b2");
A a = new A("a1", "a2", b);
A clonedA = SerializationUtils.clone(a);
assertThat(clonedA, is(not(sameInstance(a))));
assertThat(clonedA.getA1(), is(a.getA1()));
assertThat(clonedA.getA2(), is(a.getA2()));
assertThat(clonedA.getB(), is(not(sameInstance(b))));
assertThat(clonedA.getB().getB1(), is(b.getB1()));
assertThat(clonedA.getB().getB2(), is(b.getB2()));
}
static class A implements Serializable {
private String a1;
private String a2;
private B b;
public A(String a1, String a2, B b) {
this.a1 = a1;
this.a2 = a2;
this.b = b;
}
public String getA1() {
return a1;
}
public void setA1(String a1) {
this.a1 = a1;
}
public String getA2() {
return a2;
}
public void setA2(String a2) {
this.a2 = a2;
}
public B getB() {
return b;
}
public void setB(B b) {
this.b = b;
}
}
static class B implements Serializable {
private String b1;
private String b2;
public B(String b1, String b2) {
this.b1 = b1;
this.b2 = b2;
}
public String getB1() {
return b1;
}
public void setB1(String b1) {
this.b1 = b1;
}
public String getB2() {
return b2;
}
public void setB2(String b2) {
this.b2 = b2;
}
}
}
보는 바와 같이 deep copy한다.
static inner 클래스 (Class)가 아닌 inner 클래스 사용 시 다음과 같은 예외에 직면한다.
Caused by: java.io.NotSerializableException: samples.java.org.apache.commons.lang3.SerializationUtilsTests
당연히 테스트 클래스 자체를 Serializable로 만드는 것보다 static inner 클래스로 만드는 것이 바람직하겠다.
Reference:
http://stackoverflow.com/questions/4081858/about-java-cloneable
댓글을 달아 주세요