Reputation: 309
If the class name is known as a string, is it possible to construct an instance of that class? Example:
var className:String = "MyClass";
var obj:* = new getClass(className)();
Upvotes: 0
Views: 118
Reputation: 16085
While the given answers are correct, this might not work if you are using application domains.
To take into account application domain, use the following method:
public static function forName(name:String, applicationDomain:ApplicationDomain = null):Class {
applicationDomain ||= ApplicationDomain.currentDomain;
var result:Class;
while (!applicationDomain.hasDefinition(name)) {
if (applicationDomain.parentDomain) {
applicationDomain = applicationDomain.parentDomain;
} else {
break;
}
}
try {
result = applicationDomain.getDefinition(name) as Class;
} catch (e:ReferenceError) {
throw new ClassNotFoundError("A class with the name '" + name + "' could not be found.");
}
return result;
}
var myClass:Class = forName(className);
var instance:Object = new myClass();
This method and many other utilities are available in the AS3Commons Lang library
Upvotes: 2
Reputation: 1531
Yes it is!
var myClass:Class = getDefinitionByName(className) as Class;
var instance:Object = new myClass();
Upvotes: 0
Reputation: 42166
Try this:
import flash.utils.getDefinitionByName;
var className:String = "MyClass";
var obj:Object = new (getDefinitionByName(className) as Class)();
Upvotes: 1
Reputation: 1151
It is possible. You have to use getDefinitionByName(name:String):Object
Make shure that the class you are referencing is available in the swf file
var ClassReference:Class = getDefinitionByName("flash.display.Sprite") as Class;
var instance:Object = new ClassReference();
Upvotes: 2