从 class 名称运行时访问静态变量

Accessing static variable from class name runtime

如何通过在运行时知道其名称来访问 class 的静态变量?

我将 classes 的实例(我知道肯定有静态字段 'id')存储在 Array of Parent 接口中。我可以在编译时使用宏轻松获得 'id',但在运行时很难做到。

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));
        }
    }
}

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

您仍然可以在 Type.getClass 的 return 上使用 Reflect.field

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

complete example

请记住添加 @:keep 以防止未使用的字段被 Dead Code Climination (DCE) 删除。