Haxe Code Cookbook
Haxe programming cookbookBeginnerInvoke object method by string

Invoke object method by string

Reading time: 1 minute

To invoke method by it's name you will need to use Reflection API.

Snippet bellow shows how to use a string as a object method identifier to invoke it.

Usage

class MyClass {
    public function new () {}
    @:keep public function printName() {
        trace("MyClass printName is invoked");
    }
}

class Main {
    static function main() {
        var myObject = new MyClass();
        var fn = Reflect.field(myObject, "printName");
        Reflect.callMethod(myObject, fn, []);
    }
}

Haxe has dead code elimination (DCE) which remove from generated code classes, methods and variables not used from directly. In the example, method printName() is used by reflection and has no referencies anywhere else, so it will be removed in compile time. To keep printName() method after compilation switch off DCE or mark this method by @:keep metadata.

Tip: Haxe has a wonderful type system, use this as much as possible. Reflection can be a powerful tool, but it's important to know it can be error prone, since the compiler can never validate if what you're doing makes sense and is also harder to optimize.

More information:


Contributors:
Mark Knol
Aliaksei Kalanitski
Last modified:
Created:
Category:  Beginner