A time for re’flex’tion
Any of you who use Java and C# know about reflection. Wikipedia has a definition here, but basically it allows the application to self interrogate itself and figure out things during runtime. 2 actionscript methods come to mind when I think of reflection.
getQualifiedClassName and getDefinitionByName both in the flash.utils package.
So I wanted to tell Flex to create a button without coding a ‘new mx.controls.Button’, so how is this done? Well with reflection.
Lets take a look at the Create method below. It takes an undefined data type, a string, two integers and two optional integers. The last four parameter are obvious so I will talk about the first one, objClass. This is where you tell Flex what kind of object to create, you pass in the class name like Button, List, etc and Flex will get the class name from the object, create a reference to it and then create an instance of that reference. Then it will return the object so you can use it, set data, add events, etc.
public function Create(objClass:*, strTitle:String, X:int, Y:int, iWidth:int = -1, iHeight:int = -1):*
{
var strClass:String = flash.utils.getQualifiedClassName(objClass);
var objViewRef:Class = null;
var objView:Object = null;
objViewRef = flash.utils.getDefinitionByName(strClass) as Class;
objView = new objViewRef();
if(objView.hasOwnProperty(“label”) == true)
objView.label = strTitle;
objView.x = X;
objView.y = Y;
if(iWidth != -1)
objView.width = iWidth;
if(iHeight != -1)
objView.height = iHeight;
addChild(objView as DisplayObject);
return objView;
}
To create objects:
var objButton1:Button = Create(Button, “Button 1″, 10, 10);
var objList:List = Create(List, “List 1″, 10, 100, 100);
var objComboBox:ComboBox = Create(ComboBox, “ComboBox 1″, 10, 300, 100);
