Mar 18 2007
Instantiating ActionScript 3.0 classes at runtime, and a Flex compiler trick
I’ve been playing around with dynamically instantiating classes in AS 3.0 a lot lately and I thought I would share a couple of tricks that I’ve come across.
You can instantiate a class at runtime using the getDefinitionByName(name:String):Object method in the flash.utils package. To use this method, you simply have to pass it the name of the class that you want to create.
Here are couple good posts that explain how to use this method:
Both of these posts point out that one of the limitations of this method is that the class that you want to create needs to be compiled into your application and that Flex only compiles in classes that are explicitly referenced in your application. This is obviously a major drawback, since one the main reasons that you would want to use dynamic instantion is to create classes that are not already referenced in you app.
So, I did a little searching and I found that there is a way to instantiate a class at runtime that is not explicitly referenced in your application.
Here’s how:
1. Put the classes that you want to instantiate at runtime in a Flex Library Project.
2. In the project for your application, add the .swc that is generated by the library project to the library path.
3. In the compiler arguments for your application add -include-libraries <path_to_swc>
The -include-libraries compiler argument tells the compiler that you want to load all of the classes in the library, even the ones that are not referenced anywhere.
Once you’ve done this, you will be able to load any of the classes in the library at runtime.
Now for the compiler trick:
If you go into the application that loads the library and create classes that have same name and namespace as the classes in your library project, the compiler will load the classes that are in your main application. This means that the library project only needs to contain empty classes that mirror the classes in your application that you want to instantiate at runtime.
For example, let’s say that you have a class called GetUser that you want to instantiate at runtime. If you follow the instructions from above you will have a Flex Library Project and Flex application that loads the SWC that is generated by the library.
Now, let’s say that you’ve put the AddUser class in the following package in your library project
com.mycomp.myproj.command.AddUser
If you put an AddUser class in the com.mycomp.myproj.command package in your Flex application project, when you instantiate the class at runtime the Flex will create the class that is in your Flex application project.
WARNING: The tricks that I described seem to make Flex very unhappy. If you want to test them out I suggest that you use new projects in a new workspace.
Please let me know if you have any questions about any of this.
