Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 307
vbence Avatar asked Dec 06 '11 10:12

vbence


1 Answers

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 _:
        }
    }
}
like image 149
Waneck Avatar answered Sep 24 '22 00:09

Waneck