Creating a component instance by class name in ActionScript 3.0

The following example shows how you can create a new Flex component instance by using its class name by calling the getDefintionByName() method.

Full code after the jump.

In the following example, note that we must include a reference to each of the components we may need to create at runtime in a variable, dummyArr. This way, the components we need are compiled in to the SWF so they can be created at runtime.


<?xml version="1.0" encoding="utf-8"?>
<!-- -->
<mx:Application name="getDefinitionByName_test"

            import mx.core.UIComponent;
            import flash.utils.getDefinitionByName;
            import mx.controls.*;

             * Create references to component classes so the classes get
             * included in the SWF document.
            private var dummyArr:Array = [Button, CheckBox, ComboBox,
                                            List, TextInput, TextArea];

            private function createBtn_click(evt:MouseEvent):void {
                var className:String = comboBox.selectedItem.toString();
                // Convert class name to Class object.
                var cls:Class = getDefinitionByName(className) as Class;

                // Create a new instance of the class.
                var instance:UIComponent = new cls();
                if (instance) {
                    switch (instance.className) {
                        case "Button":
                            Button(instance).label = "I am a Button";
                        case "CheckBox":
                            CheckBox(instance).label = "I am a CheckBox";
                        case "ComboBox":
                            ComboBox(instance).dataProvider = ["I am a ComboBox"];
                        case "List":
                            List(instance).dataProvider = ["I am a List"];
                            instance.width = 100;
                        case "TextInput":
                            TextInput(instance).text = "I am a TextInput";
                        case "TextArea":
                            TextArea(instance).text = "I am a TextArea";

                    // Remove all children and add new child.

    <mx:ApplicationControlBar dock="true">
        <mx:Form styleName="plain"
            <mx:FormItem label="Class:"
                <mx:ComboBox id="comboBox">
                <mx:Button id="createBtn"
                        click="createBtn_click(event);" />

    <mx:Canvas id="canvas"
            verticalCenter="0" />


View source is enabled in the following example.

10 thoughts on “Creating a component instance by class name in ActionScript 3.0

  1. Thanks for the code. Works perfect.

    Let’s say you created 10 components. And then you want to reference those components in actionscript. How would you do so?

    For example, let’s say you wanted to dynamically change the background of one of the components. How you you write the actionscript (instance.backgrouColor = #000000 ??? )


  2. andrew,

    You could use getChildAt() or getChildByName() to access the dynamically created component instances. Something like the following:

    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx=""
                import flash.utils.getDefinitionByName;
                import mx.controls.Button;
                private const dummyArr:Array = [Button];
                private function init():void {
                    var c:Class = getDefinitionByName("mx.controls.Button") as Class;
                    var idx:uint;
                    var len:uint = 5;
                    for (idx = 0; idx < len; idx++) {
                        var obj:Button = new c();
                        obj.label = "Button " + idx;
               = "button" + idx;
                private function btn_click(evt:MouseEvent):void {
                    var b:Button = getChildByName("button3") as Button;
                    b.label = "OUCH";
        <mx:ApplicationControlBar dock="true">
            <mx:Button id="btn"
                    label="Change Button 3"
                    click="btn_click(event);" />


  3. Thank you so much Peter – that makes a lot of sense.However, for some reason, my code is throwing an error: “Cannot accesss the property of a null object…”

    This is my code in a nutshell:

    The following code is in a loop where “contentType” changes between Text, TextArea and Image. It outputs perfectly (thanks to you!).

    var c:Class = getDefinitionByName('mx.controls.'+contentType) as Class;
    var obj:UIComponent = new c();
    if (obj) {
    switch (obj.className) {
        case "Text":
            Text(obj).id = contentID;
            Text(obj).text = content;
            Text(obj).x = contentxPos;
            Text(obj).y = contentyPos;
            Text(obj).width = contentWidth;
            Text(obj).height = contentHeight;
            Text(obj).styleName = contentStyleName;
        case "TextArea":
            TextArea(obj).id = contentID;
            TextArea(obj).text = content;
            TextArea(obj).x = contentxPos;
            TextArea(obj).y = contentyPos;
            TextArea(obj).width = contentWidth;
            TextArea(obj).height = contentHeight;
            TextArea(obj).styleName = contentStyleName;
        case "Image":
            Image(obj).name = "54237";
            Image(obj).id = contentID;
            Image(obj).source = contentSource;
            Image(obj).x = contentxPos;
            Image(obj).y = contentyPos;
            Image(obj).width = contentWidth;
            Image(obj).height = contentHeight;
            Image(obj).setStyle('completeEffect', slowFade);
            Image(obj).addEventListener(MouseEvent.CLICK, showImageGallery);
            Image(obj).addEventListener(FlexEvent.CREATION_COMPLETE, creationCompleteHandler);

    …but then I use:

    var i:Image = getChildByName("54237") as Image;
    i.source = '/myimage.jpg';

    And it doesn’t work. Note that I just hardcoded “54237” for testing…

    Any suggestions ???

    Thanks again!

  4. Quote “we must include a reference to each of the components we may need to create at runtime in a variable”.

    How do we include a dynamic reference? Say, I have my own component called “MyButton”, which is dynamically loaded from database or xml file at runtime. In another word, I don’t the class name of my component at the coding/compiling time

  5. How about an icon or image class


    public var saveIcon:Class;

  6. solved the problem for icon/image class

    public var saveIcon:Class;

    var iconSource:String = “saveIcon”;

    var ImageClass:Class = this[iconSource] as Class;
    button.setStyle(“icon”, ImageClass);

  7. Hi, I know it’s old thread but I got similar problem as andrew and can’t find straight answer. All would be great but I use addElement in place of addChild. For examples sake let’s say I add a button with id “button1”. If I use mxml I can simply call it by using this[“button1”], but when I use pure ActrinScript I get an error saying that value doesn’t exists or is null. Only way I found so was was to make custom array and add reference to this component (array_name[“button1”]), but I don’t really like this way around and want to use this[“button1”] same like for mxml components. Could you point me in the right direction?

Comments are closed.