Search code examples
reflectionhaxe

Get the type of a field in Haxe (reflection api)


I have a class:

class MyClass {
    private var num : Int;
}

I would like to know that the field has the type Int regardless of the current value which can be null for example.


Solution

  • You can't do it at runtime without compile-time information. You can do this with either RTTI, or with macros. RTTI would be easier to implement, albeit it might be a little slower if you'd need to parse RTTI multiple times.

    Your class would then become:

    @:rtti
    class MyClass {
        private var num : Int;
    }
    

    and to get the field type:

    var rtti = haxe.rtti.Rtti.getRtti(MyClass);
    for (field in rtti.fields) {
        if (field.name == "num") {
            switch (field.type) {
                case CAbstract(name, _):
                    trace(name); // Int
                case _:
            }
        }
    }