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

1

8

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.

Peeling answered 6/12, 2011 at 10:54 Comment(0)
P
5

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 _:
        }
    }
}
Panlogism answered 6/12, 2011 at 13:54 Comment(5)
Thanks for the answer. Is there any way to add this information manually to the class (to some magic hidden field)? XML seems to be a huge overkill.Peeling
yes, but you'd need to use macros. The easiest way would be to use a build macro ( haxe.org/manual/macros/build )Panlogism
but you can also do the xml parsing oncee and store the result in a static fieldPanlogism
Build macros look also promising. The documentation was kinda hidden on the page. Thanks again.Peeling
Also maybe you can do this with a normal macro and Context.typeof(otherExpr). The signature of this macro would be something like @:macro static function getDeclaredTypeOfField(class:Expr, field:String):StringPanlogism

© 2022 - 2024 — McMap. All rights reserved.