Josh Bloch wrote in the Effective Java:
Many consider clone and Cloneable broken in Java, largely because the rules for overriding clone are tricky and difficult to get right
and he recommends use clone constructor.
Sonar has rule "clone" should not be overridden forbidding use clone method. And Sonar recommends use clone constructor too.
I tried to use clone constructor and I got a some problem.
I have class with generics:
public class ClassA<T extends InterfaceB>
{
private T fieldB;
}
I have 3 implementation of InterfaceB: ClassB1, ClassB2, ClassB3. And I would like implement deep clone constructor for the ClassA.
I tried to do so:
//...
public ClassA(ClassA object)
{
if (object.fieldB instanceof ClassB1 objectB1)
{
this.fieldB = new ClassB1(objectB1);
}
if (object.fieldB instanceof ClassB2 objectB2)
{
this.fieldB = new ClassB2(objectB2);
}
if (object.fieldB instanceof ClassB3 objectB3)
{
this.fieldB = new ClassB3(objectB3);
}
}
//...
I think this code is awful:
- If somebody add new implementation ClassB4 he should add new if block in this constructor. I think with 100% chance they will forget to do. This will result in a clone error.
- This code is hard to read
When I using the classic method "clone" I don't have this problem. I call object.field.clone() and it works.
I have a question: What is the best way to deep clone by constructor if case uses generic fields