Loading Classes Dynamically in ActionScript 3

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:

  1. Declare the class somewhere in the code.
  2. 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:

-includes=com.mydomain.package.MyClass

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:

  1. Right-click on your project.
  2. Choose “Properties”.
  3. Select “Flex Compiler”.
  4. Enter your arguments in the “Additional compiler arguments” section.

As an aside, you can use the flash.utils.getQualifiedClassName and flash.utils.getQualifiedSuperclassName functions to get the fully qualified class name of an object instance.