问题
In Haxe, it is possible to get the class of an object with the following function:
Type.getClass(myObject);
If the object myObject
is an instance of the class myClass
, which contains a static field, I should be able to access this static field:
class MyClass
{
public static myStaticField:Int = 5;
}
public var myObject = new MyClass();
//expected trace: "5"
trace (Type.getClass(myObject).myStaticfield);
But the result is:
"Class <MyClass> has no field myStaticField."
Any idea why?
回答1:
You need to use reflection to get such value:
class Test {
@:keep public static var value = 5;
static function main() {
var test = new Test();
var v = Reflect.field(Type.getClass(test), "value");
trace(v);
}
public function new() {}
}
Note that to prevent DCE (dead code elimination) I had to mark the static var with @:keep
. Normally DCE is going to suppress that variable because it is never referred directly.
Working example here: http://try.haxe.org/#C1612
回答2:
Try the Reflect class (Specifically the callMethod or getProperty functions).
来源:https://stackoverflow.com/questions/31746718/why-is-it-not-possible-to-access-static-fields-of-a-class-via-type-getclass