Reflections in the Actionscript3.0/flex2
In ActionScript 3, you will find a series of functions in the Flash.utils package that provide reflection. The main features include the following:
* Determine the class of the object
* Get information about members, methods, constructors, and parent classes of a class
* Constants and methods for determining interface declarations
* Create an instance of a class based on the class name at run time
* Gets or sets the value of an object member at run time based on member name
* Method of invoking an object at run time according to the method name
You can use a feature like "Describetype" that returns an XML object. To give an example:
Package {
Import Flash.display.Sprite;
Import Flash.utils.describeType;
public class Describetypeexample extends Sprite {
Public Function Describetypeexample () {
var child:sprite = new Sprite ();
var description:xml = Describetype (child);
Trace (description. Accessor. @name. toxmlstring ());
}
}
}
If you want to further, create an instance of the object based on the class name, we can use "getdefinitionbyname ()"
Package {
Import Flash.display.DisplayObject;
Import Flash.display.Sprite;
Import Flash.utils.getDefinitionByName;
public class Getdefinitionbynameexample extends Sprite {
private var bgcolor:uint = 0xffcc00;
private var size:uint = +;
Public Function getdefinitionbynameexample () {
var classreference:class = Getdefinitionbyname (" Flash.display.Sprite ") as Class;
var instance:object = new Classreference ();
Instance.graphics.beginFill (BgColor);
instance.graphics.drawRect (0, 0, size, size );
Instance.graphics.endFill ();
AddChild (Displayobject (instance));
}
}
}
Although this is a very handy approach, there are a number of limitations to using reflection in Flashplayer because of the lack of runtime dynamic source compilation. The above features are undoubtedly useful for the built-in classes, such as the Sprite class, but we have a lot of trouble with custom classes. Like what:
Package {
Import com.customtypes.string; Custom String Implementation Class
Import Flash.utils.getDefinitionByName;
public class Getdefinitionbynameexample {
Public Function Getdefinitionbynameexample () {
var classreference:class = getdefinitionbyname ("com.customtypes.string") as Class;
var instance:object = new Classreference ();
Instance.customparameter = "my parameter";
}
}
}
Although we used the import statement, "Getdefinitionbyname ()" still fails. As mentioned above, compiling source code at run time is not allowed. Maybe we can do it later. In the present case, to implement the above function, at least initialize an instance of a class in your code. That is, declaring an instance of a class:
var customType:com.customtypes.string;