How to clone an Object (NOT an SObject!) with apex?

Assume there is a custom class foo:

class foo {
  // ... some member variables here
}

and an instance of it

foo fooInstance1 = new foo();

how to make an independent copy fooInstance2 and not only an reference like that:

foo fooInstance2 = fooInstance1;

Update

There is an additional challange, that I can’t serialize the class, because some of the members are unserializable (like DescribeFieldResult or Exception)

Answer

The other “practical” way to do this through JSON:

Foo a = new Foo();
Foo b = (Foo)JSON.deserialize(JSON.serialize(a), Foo.class);

That said, JSON is majorly expensive, so you’re better off writing your own copy constructor (as mentioned by @DerekF), which would be used like this:

Foo a = new foo();
Foo b = new foo(a);

I would suggest you post an Idea for this.

Attribution
Source : Link , Question Author : Uwe Heim , Answer Author : sfdcfox

Leave a Comment