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.

vbence
  • 20,084
  • 9
  • 69
  • 118

1 Answers1

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 _:
        }
    }
}
Gama11
  • 31,714
  • 9
  • 78
  • 100
Waneck
  • 2,450
  • 1
  • 19
  • 31
  • 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. – vbence Dec 06 '11 at 14:06
  • yes, but you'd need to use macros. The easiest way would be to use a build macro ( http://haxe.org/manual/macros/build ) – Waneck Dec 06 '11 at 14:10
  • but you can also do the xml parsing oncee and store the result in a static field – Waneck Dec 06 '11 at 14:11
  • Build macros look also promising. The documentation was kinda hidden on the page. Thanks again. – vbence Dec 06 '11 at 14:43
  • 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):String – Waneck Dec 06 '11 at 14:50