Create object from string of class name

Here’s a commonly asked question on how to instaniate an object from the name of a class at runtime:

To instantiate a class from a string of its name at runtime, the class needs to be referenced first. For example:

import MyClass; // optional
var tmp = MyClass;
delete tmp;

// construct the class name anyway you want
var dynamicClass:String = "MyClass";

// instantiate an object
var obj = new (eval(dynamicClass));

A related article I posted in 2002 (using ActionScript 1.0):

Invoking a dynamic class method: http://quantumwave.com/flash/dynamicMethod.html

9 thoughts on “Create object from string of class name

  1. I like the “factory” method when i have more than one dynamic class, ie

    var dynamicClass:String = “class name”;
    switch(dynamicClass) {
    case ‘foo’:
    return new foo();
    break;
    case ‘oof’:
    return new oof();
    break;
    default:
    trace(“there is no ” + dynamicClass);
    }

    this way your classes still get compiled into the swf and you have to instance and then delete the instance….etc..

  2. opps

    this line:

    this way your classes still get compiled into the swf and you have to instance and then delete the instance….etc..

    should be:

    this way your classes still get compiled into the swf and you DON’T have to instance and then delete the instance….etc..

    sorry!

  3. Hi,

    Is there a way to create a class from a dynamic class name in Flash 8? Can’t seem to get this to work. My class is in a namespace. Is that causing the problem?

    Thanks!

    Matt

  4. Sounds like a great thingy. I tried using it to instantiate classes from the tagnames in an xml document, but it did not work, oddly enough.

    var func = eval(“Buddies”);
    trace(func); //output: [type Function]
    trace(somNode.nodeName) //output: Buddies
    func = eval(someNode.nodeName);
    trace(func); //output: undefined

    So why would that be?

    Regards, Karel

  5. var ClassReference:Class = getDefinitionByName(“flash.display.Sprite) as Class;
    var instance:Object = new ClassReference();
    addChild(DisplayObject(instance));

    For more info: check the help and look for getDefinitionByName

Leave a Reply

Your email address will not be published. Required fields are marked *

54 ÷ six =