'actionscript3' tag

Creating Instances from the Library with Strings

0

Problem: while working on an AS3 document you uncover an unusual situation in which you have a string class name that corresponds to something in the library. How does one do it?

I’ve come across this a number of times and found myself dropboxing this snippet so I would always have it with me …

import flash.utils.*;

/**
 * Takes a string classname, returns an instance of that class, if it exists.
 */

private function newInstanceFromString(className:String):*{
    try{
        var classRef:Class = getDefinitionByName(className) as Class;
        return new classRef();
    } catch( e:ReferenceError ){
        trace('Error: there was a problem creating an instance of the "'+className+'" class. Check your library and linkage to ensure it\'s there.');
        trace(e+"\n");
    }
}

See the AS3 livedocs for more information about getDefinitionByName, the super helpful method that makes it all work.