Clone a object with type cast
January 29th, 2009
Wheel, I’m not writing another way of do it…
Is the same way that ObjectUtils of Flex Framework do, but… Imagine that we want to duplicate one object of the class Example, we can just do the clone with a code like this:
public function deepClone ( obj : * ) : *
{
var bytes : ByteArray = new ByteArray();
bytes.writeObject(obj);
bytes.position = 0;
return bytes.readObject();
}
Let’s first imagine our Example class like this:
package com.filipesilvestrim
{
public class Example
{
public var name : String;
public function Example () {}
}
}
Ok, but now if we try get the object with the cast like trace((deepClone(obj) as Example)). Man… shame on you, you’ll get “null”. but why? It occurs because when we are cloning the class we do it with the ByteArray and when you return that’s “new” bytes as an Object, the Flash Player don’t know that those bytes are affiliate with the class Example. So how to solve it?
Let’s register in the Flash Player the class Example, to that when it saw the bytes being cast, it understand that those bytes mean that class. To register we need to this:
registerClassAlias("com.filipesilvestrim.Example", Example);
And the code working will be like this:
package com.filipesilvestrim
{
import flash.net.registerClassAlias;
import com.filipesilvestrim.Example;
public class MainClone
{
public function MainClone ()
{
var obj : Example = new Example();
registerClassAlias("com.filipesilvestrim.Example", Example);
trace("Cloned Object with cast = " + (deepClone(obj) as Example)); // must trace "Cloned Object with cast = [object Example]"
}
private function deepClone ( obj : * ) : *
{
var bytes : ByteArray = new ByteArray();
bytes.writeObject(obj);
bytes.position = 0;
return bytes.readObject();
}
}
}
So, lets code and have fun
