【问题标题】:Get type of class field with null value in Haxe在 Haxe 中获取具有空值的类字段的类型
【发布时间】:2017-04-04 15:28:25
【问题描述】:

是否可以在haxe中获取具有空值的字段类?

“Type.getClass”函数获取值类(在运行时设置),但我需要在编译时获取类。

函数“getClassFields”只返回字段名,不返回类。

例如:

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

在我的情况下,我无法更改 MyCls 类的来源。

谢谢。

【问题讨论】:

    标签: class types metaprogramming haxe neko


    【解决方案1】:

    你可以试试Runtime Type Information。这是一个 Haxe 功能,允许在运行时获取类型的完整描述。 http://haxe.org/manual/cr-rtti.html

    【讨论】:

      【解决方案2】:

      由于您需要获取空字段的类型,因此您确实需要求助于 Haxe 的运行时类型信息 (RTTI)(推荐为 @ReallylUniqueName)。

      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));
          }
      }
      

      现在,显然,有一个问题......

      RTTI 需要 @:rtti 元数据,但您说不能更改 MyCls 类来添加它。然后解决方案是通过构建文件中的宏添加它。例如,如果您使用的是 .hxml 文件,它应该如下所示:

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

      有了这个和您自己的 MyCls 定义,输出将如下所示:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多