After the previous success of PixLib dealing with my configuration needs, today brought a new challenge, creating instances at runtime from string identifiers (aka Class Factories).
To complete part of the project im working on in a nice way I want to be able to create instances of UI classes at runtime, using their fully qualified package names as identifiers. e.g. com.relivethefuture.ui.Stage.
The package names will be specified in the config file, but the class constructors need to be passed parameters which can’t be declared in the config as well.
IF the instances could be created without parameters then I could have used the config type called ‘class’. This would have meant that the framework would have done the hard work for me and created me an instance of the class specified.
When you are able to use this feature you can setup your config like this (note the quotes around the package name and any string arguments)
The interesting thing is whilst investigating the source code to see how PixLib creates the class instance I found a handy little utility function tucked away in the HashCodeFactory class (com.bourre.core.HashCodeFactory).
This class has a static method just for building instances, it looks like this :
public static function buildInstance(sPackage:String, aArgs:Array)
Exactly what I need.
I can just specify the class name in my config file
and when the time comes I just call the buildInstance method (note the parameters are supplied as an array)
stage = HashCodeFactory.buildInstance(Config.getInstance().stage.classname,[mc.mainStage]);
Now, for those of you who are going to be creating classes from package names remember one vital thing. You *MUST* reference the class at some point in your code for the compiler to include it into the swf, otherwise you wont be able to create an instance. This is slightly unfortunate, but its easy enough to deal with, just add
static var myClass:com.mydomain.MyClass
to your main class (or in a seperate class that is just used as a placeholder to ensure the classes are imported) and you’re good to go.