Create an instance of a class from a string in ActionScript 3

I have a string that at runtime contains the name of the class I want to create. How can I do it?

I read suggestions on using flash.utils.getDefinitionByName() :

 var myClass:Class = getDefinitionByName("package.className") as Class; var myInstance:* = new myClass(); 

However, this gives me the following error:

Bug Fix [Fault], information = ReferenceError: Error # 1065: Variable variable name not defined.

+4
source share
2 answers

The easiest method I came up with is to simply write class names, separated by semicolons, anywhere in your project.

eg. I create an Assets.as file with this in it:

 package { public class Assets { // To avoid errors from the compiler when calling getDefinitionByName // just list all of the classes that are not otherwise referenced in code: Balloon; Cloud; FlyingHorse; FlyingPig; UFO; Zeppelin; } } 

A complete code sample / tutorial on this subject is here: http://producerism.com/blog/flashpunk-dame-and-lua-tutorial-part-6/

+6
source

Another option is to use the mxmlc -includes compiler argument as follows:

 -includes=com.mydomain.package.MyClass 

http://blogs.adobe.com/cantrell/archives/2010/09/loading-classes-dynamically-in-actionscript-3.html

+1
source

All Articles