Wednesday, June 20, 2012

Dynamic Creation of Specific Types at Runtime in ActionScript 3

I've seen this problem bandied about quite a bit; how do I create an instance of a given type directly from the Class, without having to declare an instance of the type somewhere to force the import?

Here's how I do it:

I take an incoming string specifying a key in an object I've created; these keys maps to Class types. I then process the class type based on the key; the trick is using getQualifiedClassName, which gets the absolute namespace, which avoids having to do the instance declaration. You could technically create that myTypes object by going through the app domain, but my need is generally satisfied by just making a table of the types available this way.

I then create the new instance and return it. It's typed as "*", but that's to be expected since I can be returning almost anything. You could always return something like { type : myType, instance : newInstance } or something if you wanted to be able to maintain the incoming typeName arg, and of course you can get that info after the fact by inspecting the returned object.

private var _myTypes : Object = { "MyType1" : MyType1, "MyType2" : MyType2 };
private function createInstance ( typeName ) : *
{
     var getType : String = flash.utils.getQualifiedClassName ( _myTypes [ typeName ] );
     var desiredClass : Class = flash.utils.getDefinitionByName ( typeName ) as Class;
     var newInstance : * = new desiredClass ( );

     return newInstance;
}

No comments:

Post a Comment