Class reflection from a static method
I am using the excellent org.as3commons.reflect and org.as3commons.lang libraries and have hit a snag. I have a static method in one of my classes that needs to do reflection on its class. The reflect library has a Type.forClass(clazz:Class) static method that clearly requires a Class variable. There is no this keyword allowed in static methods/code so now I need to know if there is a way to get the class for which my static method is being called.
I need something that will work in the non-debug version of Flash player, so any Error.getStackTrace() tricks won't work. Too bad no stack trace is available in the normal VM.
import org.as3commons.lang.ClassUtils;
import org.as3commons.reflect.Type;
protected static function doReflection(): void
{
var aClass: Class = ClassUtils.forInstance(this); // this not allowed in static methods
var c开发者_运维技巧t: Type = Type.forClass(aClass);
// do stuff with type
}
I gave up searching on Google and other sites; always ended up getting tutorials and tips on everything related to static members, performance issues, everything except what I am looking for.
Overall, I want to cache a bunch of things about the class in static members to save unnecessary work each time the class gets instantiated.
Any help would be appreciated.
what about passing a reference to the instance you need as an argument of static method?
It might not work in all situations...mainly will depend on what happens on your constructor.
import org.as3commons.lang.ClassUtils;
import org.as3commons.reflect.Type;
static private const CLASS:Object = new YourReflectedClass;
protected static function doReflection(): void {
// var aClass: Class = ClassUtils.forInstance(this); // this not allowed in static methods
var aClass:Class = CLASS.constructor;
var ct: Type = Type.forClass(aClass);
// do stuff with type
}
A better approach would be to use:
static private const CLASS:Class = YourReflectedClass;
var ct: Type = Type.forClass(CLASS);
Just wanted to show you the Object.constructor method...
i think in debug-mode you can use the stack-trace of an error object to retrieve/reflect the class from static context, but in release build you have to get the global scope to reflect:
//RELEASE BUILD
public static function whoAmI():void
{
var clsName:String = describeType((function m():*{return this})()).constant.@type;
var cls:Class = getDefinitionByName(clsName) as Class;
}
//DEBUG MODE (getStackTrace()-hack)
public static function whoAmI():void
{
var stack:Array = new Error().getStackTrace().replace("Error\n","").split("\n");
//write your stack-trace parser here
var clsName:String = ...
var cls:Class = getDefinitionByName(clsName) as Class;
}
What about this:
protected static function doReflection(): void
{
var aClass: Class = ClassThatYouAreIn as Class;
var ct: Type = Type.forClass(aClass);
// do stuff with type
}
as static methods are even not inherited...
Edit: OK, I just saw that this was already proposed...
精彩评论