ClassFinder class
Thursday, 10 March 2005In a recent project I needed to instantiate a number of objects of various classes based on configuration data coming from an XML file. Unfortunately instantiating a class at runtime is not straight forward if all you’ve got to work with is a string. What I needed was some way of getting a reference to the constructor function of a class given the fully qualified class name. Ten minutes of tinkering later, I came up with the ClassFinder class.
class com.dynamicflash.utils.ClassFinder { public static function find(package:String) : Function { var packageParts:Array = package.split(".") var obj:Object = _global; for (var i:Number = 0; i < packageParts.length; i++) { obj = obj[packageParts[i]]; } return Function(obj); } }
Feeding the ClassFinder.find() method with a fully qualified class name will return a reference to the constructor of the class. You can use this to instantiate an object of that class using new and passing any arguments to the constructor as you would normally.
import com.dynamicflash.utils.ClassFinder; var myClass:Function = ClassFinder.find("com.dynamicflash.SomeClass"); var instance = new myClass("Test");
Classes are stored in _global with nested objects representing the package hierarchy. All ClassFinder.find() does is split the package name into chunks and descent the nested objects one at a time to find the class constructor function.
So what’s the catch? Because of the way the Flash compiler works, any classes that aren’t explicitly referenced in any of your code at compile time will not be included in the SWF. This means that ClassFinder won’t be able to find them, returning undefined instead. If you want to trick the compiler into including such classes, you need to make a dependancy link to those classes from a class that is explicitly referenced in your code.
class com.dynamicflash.SomeOtherClass { public function SomeOtherClass () { ... } // Create dependancy link private static var SomeClassDependancy = com.dynamicflash.SomeClass; }
This method is used in Macromedia’s V2 component core classes to make sure they’re all included in the SWF if just one of them is referenced.
–Update–
I’ve just realised that a very similar class is included with Flash MX 2004 Professional, but adding it to your projects isn’t exactly intuitive. You have to open up the Classes common library (via Window » Other panels » Common libraries » Classes in the main menu) and drag the UtilsClasses symbol into your library. You can then use
mx.utils.ClassFinder.findClass() instead of my class.
Why Macromedia didn’t just put these classes in the standard folder I don’t know, but since using it requires extra work I’ll stick with my version of ClassFinder.







