Skip to main content
Milan Dutta (Bankers Life and Casuality) 님이 #Apex에 질문했습니다
Hi Experts,

What is the difference between Clone () and DeepClone() in Apex? When should we use what? Can someone explain with an example?

Thanks!
답변 11개
  1. 2016년 6월 3일 오전 6:12
    Hi PlatFormCloud,

    Here is a Small Example to Understand difference between them:

    I am just inserting a New Account with some fields.

    Account ac = new account(Name = 'forum', billingcity = 'Texas', phone = '9999999999');

    insert ac;

    This creates a record in the Account as shown below:

    Hi PlatFormCloud,Here is a Small Example to Understand difference between them:I am just inserting a New Account with some fields.

    Now, I am cloning it and inserting again.

    Account ac = new account(Name = 'forum', billingcity = 'Texas', phone = '9999999999');

    insert ac;

    //Cloning the above Account Record ac

    Account acCloneCopy = ac.clone(false, false, false, false);

    insert acCloneCopy;

    It creates a new copy of the record with same values, since it keeps the reference, new record ID is generated for cloned record.

    User-added image

    Now, when I try to deepclone the record:

    (Deepclone is done by keeping tru in the parameters: Syntax - clone(preserveId, isDeepClone, preserveReadonlyTimestamps, preserveAutonumber))

    Account ac = new account(Name = 'forum', billingcity = 'Texas', phone = '9999999999');

    insert ac;

    //Deep cloning the above record

    Account acCloneCopy = ac.clone(true, true, false, false);

    insert acCloneCopy;

    It shows an error, because the Id is also considered and cannot insert the deppcloned record:

    User-added image

    Best Regards,

    BALAJI

     
0/9000