montonero
montonero

Reputation: 802

Accessing static variable from class name runtime

How is it possible to access static variable of a class by knowing its name at runtime?

I store instances of classes (that I know for sure have static field 'id') in Array of Parent interfaces. I can easily get 'id' at compile time with macro, but have trouble doing so at runtime.

import Macro;

interface Parent {

}

class A implements Parent {
    static public var id = 1;
    public var myVar: String;

    public function new(name: String){
        myVar = name;
    }
}


class B implements Parent {
    static public var id = 2;
    public var myVar: String;

    public function new(name: String){
        myVar = name;
    }
}


class Test { 
    static private var components = new Array<Parent>();
    static function main() {
        var a = new A("First.");
        components.push(a);
        components.push(new B("Second."));
        var id = Macro.getId(a);
        trace(id);

        for (c in components) {
            var cc = Type.getClass(c);
            trace(Type.getClassName(cc));
            // TODO: access 'id'
          //trace(Macro.getId(cc));
        }
    }
}

code: http://try-haxe.mrcdk.com/#987dA

Upvotes: 1

Views: 121

Answers (1)

Jonas Malaco
Jonas Malaco

Reputation: 1557

You can still use Reflect.field on the return of Type.getClass.

trace(Reflect.field(cc, "id"));

complete example

Just remember to add @:keep to prevent unused fields from being removed by Dead Code Climination (DCE).

Upvotes: 2

Related Questions