Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

actionscript 3 - Can I create an instance of a class from AS3 just knowing his name?

Can I create an instance of a class from AS3 just knowing it's name? I mean string representation, like FlagFrance

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Create instances of classes dynamically by name. To do this following code can be used:

 //cc() is called upon creationComplete
   private var forCompiler:FlagFrance; //REQUIRED! (but otherwise not used)

   private function cc():void
   {
      var obj:Object = createInstance("flash.display.Sprite");
   }

   public function createInstance(className:String):Object
   {
      var myClass:Class = getDefinitionByName(className) as Class;
      var instance:Object = new myClass();
      return instance;
   }

The docs for getDefinitionByName say:

"Returns a reference to the class object of the class specified by the name parameter."

The above code we needed to specify the return value as a Class? This is because getDefinitionByName can also return a Function (e.g. flash.utils.getTimer - a package level function that isn't in any class). As the return type can be either a Function or a Class the Flex team specified the return type to be Object and you are expected to perform a cast as necessary.

The above code closely mimics the example given in the docs, but in one way it is a bad example because everything will work fine for flash.display.Sprite, but try to do the same thing with a custom class and you will probably end up with the following error:

ReferenceError: Error #1065: Variable [name of your class] is not defined.

The reason for the error is that you must have a reference to your class in your code - e.g. you need to create a variable and specify it's type like so:

private var forCompiler:SomeClass;

Without doing this your class will not be compiled in to the .swf at compile time. The compiler only includes classes which are actually used (and not just imported). It does so in order to optimise the size of the .swf. So the need to declare a variable should not really be considered an oversight or bug, although it does feel hackish to declare a variable that you don't directly use.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...