24 February 2008

Creating Class Instances from a DisplayObject in AS3

*** The technique below doesn't clone a class instance, but allows you to create a new class instance derived from an unknown DisplayObject ***

After selecting an item by clicking the mouse, I needed to create a new instance of the selected item to be added to an item inventory. I needed to find out what type of object was being passed into the MouseEvent handler so I could create a new object of a specific type i.e.

private function mouseHandler(e:MouseEvent):void
{
// this is only a DisplayObject - what is it?
trace(e.target);

// this is what I want to do, but how do I know if e.target is a Rock?
var newItem:IItem = new Rock();
}

The following function uses flash.utils.getQualifiedClassName() to return a string that contains the name of the class including full namespace.

It then uses flash.utils.getDefinitionByName() to return a Class object which can then be used to create a new class.

public function duplicateItem(obj:*):*
{
var className:String = getQualifiedClassName(obj).split('::').join('.');
var ClassRef:Class = getDefinitionByName(className) as Class;
var item:* = new ClassRef();
return item;
}

So to create a duplicate object, just use call the duplicateItem function. You can also cast the returned class instance, if required, as shown below:

private function mouseHandler(e:MouseEvent):void
{
var newItem:IItem = duplicateItem(e.target) as IItem;
}