Why is it not possible to access static fields of a class via Type.getClass()?

随声附和 提交于 2020-01-04 03:58:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!