AS3: Dynamic Instantiation
Posted on Mar 6, 2010 at 6:05 pm
Last updated Mar 6, 2010 at 6:30 pm
I know this trick is well documented already, but I figure the more it's out there, the easier it is to find.
Sometimes you want to create an instance of a class, but you don't know which class until runtime. This is what's called dynamic instantiation. The way you need to do this in ActionScript, generally, is as follows:
var classReference:Class =
flash.utils.getDefinitionByName("flash.display.Sprite") as Class;
var instance = new classReference();
This example is great, and more or less comes straight from the AS3 documentation.
However, try doing this with a custom class, and you may have some difficulties. The getDefinitionByName function pulls from a list of registered class names. Custom classes by default don't get added to this list until you explicitly reference the class somewhere in your code. This includes simple variable declaration (not necessarily instantiation or assignment), so one approach is to simple have a container class listing all of the classes you may need to have dynamically generated.
This solution seems a little sloppy to me, but it's more or less all we have to work with now. I propose that at the very least, use the flash.net.registerClassAlias function. It's unrelated, but it will require a reference to your custom class, and should you ever want to serialize/deserialize, it's already registered.
import flash.net.*;
import flash.display.*;
public class ClassRegTest extends Sprite {
public function ClassRegTest() {
registerClassAlias("package.path.YourClass", YourClass);
}
}
Edit: It's funny what you find when poking around old code. I just realized I had this kicking around:
public class ClassRegistry {
private static var registry:Object = {};
public static function registerClass(className:String, classObj:Class) {
ClassRegistry.registry[className] = classObj;
}
public static function getClass(className:String) {
return ClassRegistry.registry[className];
}
public static function getInstance(className:String) {
return new ClassRegistry.registry[className]();
}
}
Comments