Clone Instances and keep Class reference

While checking out the Socket class i found a cool little trick. I´m sure everyone knows of the possibility to clone an Object with the help of the ByteArray Class. This method was introduced (at least to me ;-)) by senocular here.
The function looks like this:
function clone(source:Object):* {
var copier:ByteArray = new ByteArray();
copier.writeObject(source);
copier.position = 0;
return(copier.readObject());
}
The problem was that all the class information was lost. With class information i mean type info and thinks like methods were unavailable after cloning the object. When you try this:

var t:Test=new Test();
t.test=”hallo”;
var newObj=clone(t);
out.text=newObj.test;
out.text=newObj.sayHello();

I get the following error:

TypeError: Error #1006: sayHello ist keine Funktion.
at test/::show()
at test/___Button2_click()
But there is this nice Method registerClassAlias from the flash.net package. Using this:

registerClassAlias(“de.benz.something”, Test);
var t:Test=new Test();
t.test=”hallo”;
var newObj=clone(t);
out.text=newObj.test;
out.text=newObj.sayHello();

will keep the class information intact and the call to the method will be succesfull.
Man this is sooo cool. I´m loocking forward using this in two years when my company switches to flash 9 :-)
Anyone looking for a flex developer?

cheers

Benz

I

Tweet about this on TwitterShare on FacebookShare on LinkedInShare on Google+Pin on Pinterest

5 thoughts on “Clone Instances and keep Class reference

  1. Hi… thanks for the solution.

    I found the cloned is not really a class, is it what we expected?

    Thanks

  2. almost fixes the problem, but if Test’s constructor requires a parameter, you get a runtime error when calling ByteArray.readObject(), saying that you’re missing params…

  3. If the class that you are trying to clone has any arguments in the constructor, this method of cloning fails. You’ll get an error like so: ArgumentError: Error #1063: Argument count mismatch on User$iinit(). Expected n, got 0.

    The only work around is adding “= null” to all of your constructor’s arguments. Not the most elegant solution, but it works.

  4. I tried to clone a diaplayobject(Movieclip with some frames) but the above code did’t seem to work. It throws a null object reference error. Any way to clone a displaybject ?

Leave a Reply

Your email address will not be published. Required fields are marked *