macroshaxe

In haxe macro, how can I get a type by using a Type name


In the haxe expression macro I have the following code:

var t = haxe.macro.Context.getType("h2d.Object");

I'd like to get the type without using a string. Something like this:

var t = callX(h2d.Object);

The question is what callX should be?


Solution

  • You can use type reification and then convert a ComplexType to your desired type, like so

    var t1 = Context.getType("haxe.format.JsonParser");
    var t2 = ComplexTypeTools.toType(macro:haxe.format.JsonParser);
    trace(t1, t2);
    
    TInst(haxe.format.JsonParser,[]),TInst(haxe.format.JsonParser,[])
    

    and if you need to allow passing a type to the macro, you can use Context.typeof(expr), which would give you a TType(Class<haxe.format.JsonParser>,[])