Jeff dePascale Blogging on and developing web and mobile technologies

7Apr/090

Dynamically referencing classes – getDefinitionByName()

Referencing classes at runtime may not be an everyday occurence in AS3 development, but I'm running into it more and more these days. There are two things you need to know about. The first is getDefinitionByName(). Located in the flash.utils folder, getDefinitionByName() allows you to refer to classes by their package location and name. Some example code:

var NewClass:Class = getDefinitionByName("com.classpath.ClassName") as Class;
var classObject:Object = new NewClass();

From this point you have access to an instance of the class specified in the parameter from the 'classObject' variable.

but there's a problem here - because SWF files are precompiled, you must have the class you are looking to use compiled somewhere within your SWF structure for it to be found at runtime. Otherwise, it will attempt to access something that, as far as that SWF knows, just doesnt exist. The workaround is to include references to ALL of the classes that could possibly dynamically referenced within the SWF to ensure they are compiled and available at runtime. Obviously the negative here is that you will have the added weight of all the classes in your file. An example of how to include those references looks something like this:

First, the class to contain your references:

package {
 

 public class IncludeClasses {
  
  Class1;
 Class2;

}
}

Then, you need to simply refer to that class within your SWF:

 package{

 public class Main{

  IncludeClasses;

  public function Main(){
  }
 } 
}

Simply importing the class won't work since imports are only compiled if used. Adding a reference to the class like this effectively creates a placeholder without actually compiling the code.

Regarding the file size, I suppose you could create a SWF for each Class, load the SWF, then load the class from that SWF as well, I've never come across the need. But it should theoretically work.

Share This
  • LinkedIn
  • Facebook
  • Twitter
  • Digg
  • del.icio.us
  • Google Bookmarks
  • StumbleUpon
  • Technorati
  • email
Filed under: Flash Leave a comment
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

(required)

No trackbacks yet.