【问题标题】:Generate constructor call with build macro使用构建宏生成构造函数调用
【发布时间】:2019-01-22 08:42:56
【问题描述】:

如何通过构造函数调用为 Haxe 类生成 main()(访问)方法?

例如

static function main() new App()

function new() {
    //....
}

我想用宏创建这个,像这样:

import haxe.macro.Context;
import haxe.macro.Expr;

class Build {
    macro public static function buildFields():Array<Field> {
        var fields:Array<Field> = Context.getBuildFields();
        var cls = Context.getLocalClass().get();
        var pack = cls.pack.concat([cls.name]);
        var name = pack.join(".");

        fields.push({
            name: "main",
            access: [Access.APublic, Access.AStatic],
            kind: FieldType.FFun({
                expr: macro {
                    Type.createInstance(Type.resolveClass($v{name}), []);
                },
                args: [],
                ret: null
            }),
            pos: Context.currentPos()
        });

        return fields;
    }
}
@:build(Build.buildFields())
class App {
    function new() {
        //....
    }
}

这可以很好地生成main() 方法,但我不确定如何生成new App() 而不是诉诸Type.createInstance()。

【问题讨论】:

    标签: macros haxe


    【解决方案1】:

    要生成像 new App() 这样的构造函数调用,您可以按照文档中的 here 来具体化 haxe.macro.TypePath。

    var typePath:haxe.macro.TypePath = {
        pack: cls.pack,
        name: cls.name
    }
    
    expr: macro new $typePath(),
    

    顺便说一句,我建议您使用class reification,而不是手动构造这样的字段,它可以让您使用常规的 Haxe 语法来声明字段:

    fields = fields.concat((macro class {
        public static function main() {
            new $typePath();
        }
    }).fields);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-21
      • 2016-12-16
      • 2016-07-19
      • 2017-01-23
      • 2013-05-03
      • 1970-01-01
      • 2023-03-15
      相关资源
      最近更新 更多