Cloning in Java

前端 未结 4 1712
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-04 07:18

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

4条回答
  •  [愿得一人]
    2021-02-04 07:36

    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;
    }
    }
    

提交回复
热议问题