Dynamically Instantiating New Objects in ActionScript 3.0

Let’s say you are building an application and want to be able to dynamically instantiate new objects in AS 3.0 (Flash CS3)?

Read on for the answer . . .

The syntax for doing this has drastically changed from AS 2.0, however there is still one gotcha that remains the same.

In my case, I’m not only dynamically instantiating class names, but also their reference names.

Here’s how I figured out how to do it:

// Import the getDefinitionByName util and your class
import flash.utils.getDefinitionByName;
import com.example:ExampleClass;

// Create a variable to store a reference to your new class
var classReference:ExampleClass;

// Create a class object and use getDefinitionByName to specify the name of the class you are instantiating.
var class_tempClass:Class = Class(getDefinitionByName("com.example:ExampleClass"));
classReference = new class_tempClass();

This works great.  However, what if you don’t know what classes you’ll be instantiating and want to be able to leave that open at runtime?  This is where it’s the same in 2.0.  If you don’t include the reference to the class at compile time (var classReference:ExampleClass; ) you cannot dynamically instantiate this class, regardless of whether or not it is in your class path.

As a result, you are left with having to decide which classes you might want to instantiate at runtime and somewhere in your code, include a reference to each class such that it’s included at compile time.

Another AS 3.0 programmer indicated that it might be possible to dynamically load a swf that includes a reference to that class, but you would have to load and make sure that that swf has initialized before attempting to instantiate the object.

Maybe a way to go about it is to keep a library of swf files that have the same name as the class that you want to instantiate and write a utility that will dynamically instantiate objects.  The first thing it would do is load a swf with a reference to the class, then it would instantiate the object, returning to the calling code a reference to the newly created instance.

I think I’ll give that a try and then post and update to this thread with my findings.

Leave a Reply