简体   繁体   中英

Flex/AS3 Dynamically Create class

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

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:

  • The class name must be fully qualified, meaning if your class is in a package you must include the package. Example: "path.to.my.stuff.Class1"
  • If there are no "real" references to the class in your code (a string with the class name doesn't count) it will not get compiled into your SWF, and therefor 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.
  • Using 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];

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM