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 replies on “Create object from string of class name”
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..
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!
Can you type the object var like this:
var obj:eval(dynamicClass) = new (eval(dynamicClass));
Just wondering.
Brent
Brent: ActionScript 2.0 data types are for compile-time use only, so setting a data type at runtime won’t work (and it won’t do anything).
Yeah, to use the “factory” method, your dynamic classes should implement a common datatype.
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
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
Its really helpful.
Regards,
Pranav
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