简体   繁体   中英

Haxe macro to call static method of a class

I have a set of classes, which all have the same static method (or actually a set of methods). How would I implement a macro, which would allow me to call certain method of a given class? Something like this getStaticMethod(className, methodName)(...args...) . I need this because unfortunately Class<T> doesn't provide access to static class members.

This can be done really trivially, you don't even need any "stringly typed code" (passing class and method name to the macro).

You can just pass a dot-path expression to the macro:

import haxe.macro.Expr;

class Main {
    static function main() {
        trace(resolveDotPath(haxe.Json.parse)("{}")); // {}
        trace(resolveDotPath(Math.random)()); // 0.34622209081586863
    }

    static macro function resolveDotPath(dotPath:Expr):Expr {
        return macro $dotPath;
    }
}

However - it seems like at that point, you could just call the function directly?

If you don't know what the class is at the time the macro is called, macros probably don't help you much and don't allow you to generate strictly typed code at compile time.

There's a difference between passing some Class<T> instance to a macro that could come from anywhere and passing a concrete dot path / the class name as a string literal. If the class for the call in question is not known at compile time, all the macro could do is generate the reflection code for you, since this then has to be decided at runtime .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM