I introduce some tips for reflection (not reflection of image but "programatic") of ActionScript 3.0.
I think you can easily guess the purpose of the functions from the function name.
Example usage is shown as below.
getDefinitionByName
If you would like to Class object getDefinitionByName function should help.var c:Class = getDefinitionByName("flash.display.Sprite") as Class;If you would like to know details information of Class you can use describeType, which returns class information as Xml format.
Reflective Class Instantiation
import flash.utils.getDefinitionByName; public class Instantiator { private var classRef:Class; public function Instantiator(className:String) { this.classRef = getDefinitionByName(className) as Class; } public function newInstance(...args):Object { if(args.length == 0){ return new classRef(); } else { return new classRef(args); } } }Example usage:
import flash.display.Sprite; import seedion.io.XMLExporter; // class will be instantiated at line with (*) import utils.tool.Instantiator; import utils.tool.Instantiator; public class InstantiatorExample extends Sprite { public function InstantiatorExample () { try { var instantiator:Instantiator = new Instantiator("seedion.io.XMLExporter"); // -- (*) trace(instantiator.newInstance()); } catch (err:Error) { trace(err); } } }
Utility Functions Using getDefinitionByName and describeType
I wrote some useful (hopefully) functions using getDefinitionByName and describeType.I think you can easily guess the purpose of the functions from the function name.
import flash.utils.describeType; public class ReflectionUtils { public function ReflectionUtils() { } public static function createSetterFunction(o:*, propertyName:String):Function { if (!doesSetterExist(o, propertyName)) { throw new Error("Setter for " + propertyName +" does not exist"); } return function(x:*):void { o[propertyName] = x; }; } public static function doesSetterExist(o:*, propertyName:String):Boolean { var accessors:XMLList = describeType(o)["accessor"]; var properties:XMLList = accessors.(@name == propertyName && (@access == "readwrite" || @access == "write")); for each(var property:* in properties) { return true; } return false; } public static function isSubcalssOf(clazz:Class, superClassName:String):Boolean { try{ return describeType(clazz).child("factory") .child("extendsClass").attribute("type").contains(superClassName); } catch (e:Error) { } return false; } public static function isImplementsInterface(clazz:Class, interfaceName:String):Boolean { try{ return describeType(clazz).child("factory") .child("implementsInterface").attribute("type").contains(interfaceName); } catch (e:Error) { } return false; } }
Example usage is shown as below.
var c:Class = getDefinitionByName("flash.display.Sprite") as Class; // should return true. trace(ReflectionUtils.isSubcalssOf(c, "flash.display::DisplayObject"));
コメント