R – Create instances of flex custom component by passing in type

actionscript-3apache-flexmxml

In my flex app there are a few custom components. I want to create instance of these components at runtime and assign them properties by reading in a config file.
I know how to read xml and instantiate components, however my question is about being able
to get the type of the component from the xml attribute and then creating an instance of that type.
My xml looks like this:

Best Answer

You can instantiate an arbitrary named type through ActionScript's "reflection API":

var clazz:Class = Class(getDefinitionByName("class.from.your.xml.file.Name"));
var component:Object = new clazz();

http://livedocs.adobe.com/flex/3/langref/flash/utils/package.html#getDefinitionByName()

If you get an error about the type not existing, this is because it isn't linked from elsewhere in your application and the compiler only adds classes that are referenced. You can work around this using the following compiler arg:

includes class [...]

Links one or more classes to the resulting application SWF file, whether or not those classes are required at compile time.

http://livedocs.adobe.com/flex/3/html/compilers_14.html#157203