« Private or Helper Classes in Actionscript 3 | Main | StandUP »

Actionscript 3 Class.forName

I'm sure this would be obvious for anyone that has been programming in Actionscript 3 for awhile, but coming in from the Java world I'm still trying to find the matching idioms. In particular I wanted a way to dynamically load a class based on its name. In Java this is the Class.forName() construct. Luckily AS3 also has a similar mechanism:

// return the class as a Class object
var temp:Class = flash.utils.getDefinitionByName("com.example.Sample") as Class;
// you can now call new it to create an instance along with passing constructor args
var instance:Object = new temp(arg1, arg2, ...);

If when doing this you get an "Runtime Error 1065" see this post.

Note: Update Nov 6, 2007
It looks like flash.util.getClassByName() has gone away. The example above has been updated to use the new mechanism called flash.utils.getDefinitionByName().

Tags: actionscript as3 programming

Comments

I think it's getDefinitionByName, not getClassByName, in the flash.utils package. Another example is here
Here's some handy code for getting the Class of an Object (similar to Java's getClass() or .class): function getClass(o:Object): Class { return Class(getDefinitionByName(getQualifiedClassName(o))); }