Create component by class Name

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

GetDefinition.mxml

getDefinitionByName will retrieve the class name for any components / User Defined Components.

<?xml version=”1.0″ encoding=”utf-8″?> 

<mx:Application xmlns:mx=”http://www.adobe.com/2006/mxml” layout=”absolute” creationComplete=”createComplete(event)”>
<mx:Script>
<![CDATA[
import flash.utils.getDefinitionByName;
import mx.controls.*;
private function createComplete(e:Event):void
{
var cls:Class = getDefinitionByName(“mx.controls.Button“) as Class;  //This will get the class name for Button [Class Button]
var instance:Object = new cls();  //Creating an instance based on the class definition.
instance.label=”My Button” //Accessing Label property for Button
addChild(instance as DisplayObject);  // Add instance to the stage and parse the object as DisplayObject in order to consider the Object as UI COmponent
}
]]>
</mx:Script>
</mx:Application>

For User Defined Component

var Temp:PanelComp // It needs to be added to initiate the Component to the application
var cls:Class = getDefinitionByName(“MyComp.PanelComp“) as Class; //MyComp is the folder and PanelComp is the user defined component
var instance:Object = new cls();
instance.label=”My Button”
addChild(instance as DisplayObject);