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

In Haxe, you can get an object class with the following function:

   Type.getClass(myObject);

      

If myObject is an instance of the myClass class that contains a static field, then I should be able to access that 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> does not have a myStaticField."

Any idea why?

+3


source to share


2 answers


To get this value, you need to use reflection:

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 in order to prevent DCE (dead code removal), I had to mark the static var with @:keep

. Typically the DCE will suppress this variable because it is never directly mentioned.

Working example here: http://try.haxe.org/#C1612

+3


source


Try the Reflect class (Specifically callMethod or getProperty functions).



+1


source







All Articles