Work with final fields when overlapping a clone

I am writing a class in which I have to override the clone () method with the infamous strategy "super.clone ()" (this is not my choice).

My code is as follows:

@Override
public myInterface clone()
{
    myClass x;
    try
    {
        x = (myClass) super.clone();
        x.row = this.row;
        x.col = this.col;
        x.color = this.color; 
        //color is a final variable, here the error
    }
    catch(Exception e)
    {
        //not doing anything but there has to be the catch block
        //because of Cloneable issues
    }
    return x;
}

Everything will be fine, except that I cannot initialize colorwithout using the constructor, being the final variable ... is there a way to use super.clone () and copy the final variables?

+4
source share
2 answers

Since the call super.clone();will already create a (shallow) copy of all the fields, final or not, your full method will be as follows:

@Override
public MyInterface clone() throws CloneNotSupportedException {
    return (MyInterface)super.clone();
}

, clone() ( , super.clone() Object. ( ), , , , clone() ( , , ).

+1

, , Reflection. , . .

Field f =  getClass().getDeclaredField("color");
f.setAccessible(true);
f.set(x, this.color)
+2

Source: https://habr.com/ru/post/1620920/


All Articles