Search code examples
classtypeshaxe

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


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?


Solution

  • 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