Instantiate classes by name

A couple of months ago I wanted to instantiate classes based on their name at runtime, using Flex Builder. At the time I read about the method getDefinitionByName. Everytime I tried to use it I got the error

Error #1009: Cannot access a property or method of a null object reference.   

I googled about it and found Daniel R. post on the subject. According to him

"The problem seems to be that if the runtime module makes a side-effect reference to a component, which is not included in the main application, it never really gets included in the SWF and as such causes problems when accessed"   

And his solution was to declare a static instance of the class you wanted to instantiate at runtime.

private static const classInstance:ClassToInstantiate = null;   

This *fix* becomes a problem when you have many classes to instantiate and have to declare an instante for each one. If the classes you want to instantiate are in the flash library (movieclips), there is a workaround for the problem described above.

  • When you export the Flash library, remember to check the "Export SWC".
  • Make sure you include the SWC in the Flex Builder.
  • (Here's the Magic) Just use this arguments in the compiler options:

-include-libraries $PATH_TO_SWC/LIBRARYNAME.swc 

Leave a Reply