使用build宏生成构造函数调用 [英] Generate constructor call with build macro

查看:73
本文介绍了使用build宏生成构造函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I generate a main() (access) method for a Haxe class with a constructor call?

例如

static function main() new App()

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

我想用宏创建它,就像这样:

and I want to create this with macro, like this:

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().

This generates the main() method fine, but I'm not sure how to generate new App() instead of resorting to Type.createInstance().

推荐答案

要生成诸如 new App()之类的构造函数调用,可以对

To generate a constructor call like new App(), you can reify a haxe.macro.TypePath as documented here.

var typePath:haxe.macro.TypePath = {
    pack: cls.pack,
    name: cls.name
}

expr: macro new $typePath(),

顺便说一句,我建议不要使用类修订,而不是手动构建此类字段a>,可让您使用常规的Haxe语法声明字段:

Btw, instead of manually constructing fields like that, I would suggest using class reification, which lets you use regular Haxe syntax for declaring fields:

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

这篇关于使用build宏生成构造函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆