On 4/8/07, Toby Tremayne <[EMAIL PROTECTED]> wrote:

Hi all,
I have a method which retrieves an actionscript object, and depending on
the value of one of the keys, converts it into an actionscript class.  The
issue I have is I don't know how to instantiate a class whose name
I can't hard code - can anyone help me with this?

Basically the idea is that if obj.classname = "Page"  then I need to write
oPage : Page = new Page();  dynamically.  Is there any way to do this in
actionscript?



You can use the "getDefinitionByName" function to retrieve a reference to a
Class, and then you can create an instance of that class using the "new"
operator on the Class reference.  The following is a very simplistic
demonstration of how to instantiate the instances, but in practice you will
probably want all of your dynamically-instantiated classes to implement a
common interface, and cast the instantiated objects to that interface, so
that you don't have to write a bunch of conditionals into your code every
time you add a new class:


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml";
 applicationComplete="appComplete( event );">
 <mx:Script>
   <![CDATA[
     import defaultpckg.MyClass;

     private function appComplete( event : Event ) : void
     {
       var classRef : Class = getDefinitionByName( "defaultpckg.MyClass" )
as Class;
       var myInstance : MyClass = new classRef() as MyClass;
       myInstance.message = "Done";
       myInstance.showMessage();
     }
   ]]>
 </mx:Script>
</mx:Application>


In a separate file, ./defaultpckg/MyClass.as:

package defaultpckg
{

   import mx.controls.Alert;

   public class MyClass
   {
       private var _message : String;

       public function set message( msg : String ) : void
       {
         this._message = msg;
       }

       public function showMessage() : void
       {
         Alert.show( this._message );
       }
   }
}

Reply via email to