I read one paragraph from the Internet regarding cloning. But I didn\'t quite get it, so can someone explain it clearly?
If the class has final fields, th
Not that I recommend it but one can use sun.misc.Unsafe to overwrite a value of a final field. It is highly not recommended to use this class but this post is not about that (). A sample code to overwrite a value of a final field:
public class FinalClone
implements Cloneable {
private final FinalClone finalField;
public FinalClone(FinalClone finalField) {
this.finalField = finalField;
}
@Override
protected FinalClone clone()
throws CloneNotSupportedException {
final FinalClone result = (FinalClone) super.clone();
if (finalField == null) {
return result; // no need to clone null
}
final Field unsafeField;
try {
unsafeField = Unsafe.class.getDeclaredField("theUnsafe");
}
catch (NoSuchFieldException e) {
throw new AssertionError(e);
}
unsafeField.setAccessible(true);
final Unsafe unsafe;
try {
unsafe = (Unsafe) unsafeField.get(null);
}
catch (IllegalAccessException e) {
throw new SecurityException(e);
}
// Update final field
try {
unsafe.putObjectVolatile(
result,
unsafe.objectFieldOffset(
FinalClone.class.getDeclaredField("finalField")),
finalField.clone());
}
catch (NoSuchFieldException e) {
throw new AssertionError(e);
}
return result;
}
}