Reputation: 9
I need to create somethink like this.
var s:String;
var b1:Boolean;
if (b1==true)
s="Class1()"
else
s="Class2()";
var o:Object;
o = new [s]() // create or new Class1(), or new Class2
Upvotes: 1
Views: 184
Reputation: 670
Without knowing the reasoning behind your situation, most likely what you are looking for is an Interface. First create an interface (see here for an example):
public interface MyInterface {
//Include any methods the classes should implement here
}
Then each class should implement that interface:
public class Class1 implements MyInterface
And finally, when creating them, you can do it like this:
var o:MyInterface;
if (b1 == true)
o = new Class1();
else
o = new Class2();
Upvotes: 0
Reputation: 52143
You haven't given much information so I don't know if you really need to do this, but there are a few good reasons you might, and it can be done using getDefinitionByName
:
var className:String = somethingIsTrue ? "Class1" : "Class2";
var classType:Class = getDefinitionByName(className) as Class;
if (classType)
trace(new classType());
Note that:
"path.to.my.stuff.Class1"
getDefinitionByName
will not find it. The easiest way to solve this is to put a type declaration somewhere, such as var a:Class1, b:Class2
. Another way is to put those classes in a swc
library.getDefinitionByName
is very slow (thanks @Philarmon), so to be clear: avoid this unless you really have to do it. EDIT: Here's an example of how you can do it without using a string:
var classType:Class = somethingIsTrue ? Class1 : Class2;
var instance:Object = new classType();
As you can see, you don't have to use a string if you actually know the class name ahead of time. In fact cases where you don't know the class name ahead of time is rare.
Even if you are starting with a string (say from JSON serialized user data), as long as you know the class names ahead of time you can map the strings to class references:
var classes:Object = {
"alfa": Class1,
"bravo": Class2
}
var className:String = "alfa";
var instance:Object = new classes[key];
Upvotes: 1