Loading classes dynamically in ActionScript 3 is easy, but there are a couple of tricks to keep in mind.
First of all, to load a class dynamically, use the
flash.utils.getDefinitionByName function. Be sure to pass in the fully qualified class name, like this:
var MyClass:Class = getDefinitionByName("com.mydomain.package.MyClass") as Class; var myInstance:MyClass = new MyClass();
Easy enough. But there’s something to watch out for. Class definitions only get compiled into your SWF if they’re declared somewhere in your code. In other words, if
MyClass was never declared, the class definition wouldn’t be included in your SWF, and you would get a runtime error when trying to load it dynamically. (Note that this is not the case for classes native to the runtime — only your own custom classes.) Even importing the class isn’t enough to get it included — it must actually be declared.
There are two ways to work around this issue:
- Declare the class somewhere in the code.
- Use a command line argument to force the class definition to be included.
Below is an example of declaring the class before loading it dynamically:
MyClass; // or var mc:MyClass; var MyClass:Class = getDefinitionByName("com.mydomain.package.MyClass") as Class; var myInstance:MyClass = new MyClass();
This works fine, but in my opinion, it may defeat the purpose of loading a class dynamically. Usually you want to load classes dynamically because you’re not sure until runtime which class you’re going to want. If you knew which classes you wanted before you loaded them dynamically, you could just instantiate them directly.
The other option is to use the mxmlc
-includes compiler argument like this:
Now, the class definition will be compiled into your SWF, and you can load it dynamically anytime you want without ever having to declare it.
To specify compiler arguments in Flash Builder, follow these steps:
- Right-click on your project.
- Choose “Properties”.
- Select “Flex Compiler”.
- Enter your arguments in the “Additional compiler arguments” section.