【问题标题】:Accessing static variable from class name runtime从类名运行时访问静态变量
【发布时间】:2017-11-07 18:09:40
【问题描述】:

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

我在父接口数组中存储类的实例(我知道肯定有静态字段“id”)。我可以在编译时使用宏轻松获取 '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

【问题讨论】:

    标签: macros haxe


    【解决方案1】:

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

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

    complete example

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

    【讨论】:

      猜你喜欢
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 2012-09-06
      • 2015-07-22
      • 2012-06-29
      • 1970-01-01
      相关资源
      最近更新 更多