为什么不能通过Type.getClass()访问类的静态字段? [英] Why is it not possible to access static fields of a class via Type.getClass()?
问题描述
在Haxe中,可以使用以下函数获取对象的类:
In Haxe, it is possible to get the class of an object with the following function:
Type.getClass(myObject);
如果对象 myObject 是类 myClass ,其中包含一个静态字段,我应该可以访问此静态字段:
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);
但结果是:
Class
"Class <MyClass> has no field myStaticField."
任何想法为什么?
推荐答案
您需要使用反射来获得这样的值:
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() {}
}
$ b b
注意,为了防止DCE(死代码消除),我不得不标记静态var与 @:keep
。通常,DCE将禁止该变量,因为它从不直接引用。
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.
这里的工作示例: http://try.haxe.org/#C1612
这篇关于为什么不能通过Type.getClass()访问类的静态字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!