Search code examples
classtypesmetaprogramminghaxeneko

Get type of class field with null value in Haxe


Is it possible to get class of field with null value in haxe?

The function "Type.getClass" gets class of value (setted at runtime), but I need to get class defined in a compilation-time.

Function "getClassFields" returns only names of fields, without classes.

For example:

class MyCls
{
   public static var i:Int = null;
   public static var s:String = null;
}

trace(Type.getClass(MyCls.i)); // show "null", but I need to get Int
trace(Type.getClass(MyCls.s)); // show "null", but I need to get String

And in my situation I can't to change sources of class MyCls.

Thanks.


Solution

  • Since you need to get the types for null fields, you really need to resort to Haxe's Runtime Type Information (RTTI) (as @ReallylUniqueName recomended).

    import haxe.rtti.Rtti;
    import haxe.rtti.CType;
    
    class Test {
        static function main()
        {
            if (!Rtti.hasRtti(MyCls))
                throw "Please add @:rtti to class";
            var rtti = Rtti.getRtti(MyCls);
            for (sf in rtti.statics)
                trace(sf.name, sf.type, CTypeTools.toString(sf.type));
        }
    }
    

    Now, obviously, there's a catch...

    RTTI requires a @:rtti metadata, but you said you cannot change the MyCls class to add it. The solution then is do add it through a macro in your build file. For instance, if you're using a .hxml file, it should then look like:

    --interp
    --macro addMetadata("@:rtti", "MyCls")
    -main Test
    

    With this and your own MyCls definition, the output would look like:

    Test.hx:11: i,CAbstract(Int,{ length => 0 }),Int
    Test.hx:11: s,CClass(String,{ length => 0 }),String