如何检索声明上的注释

时间:2014-05-28 06:32:35

标签: dart dart-mirrors

根据规范,元数据可以出现在变量声明之前。

但是,它没有说明是否可以检索。

const annotation = null;

main() {

  @annotation
  var a = "";
  print(reflect(a) is DeclarationMirror);
}

输出false;

是否可以检索这种注释用法?

4 个答案:

答案 0 :(得分:2)

对于anwser抱歉,但实际上,它不可能做你想要的。 原因很简单:您的代码在语法上是正确的,但没有创建注释的实例。

示例:

class Testing {
  Testing(String toPrint) {
    print(toPrint);
  }
}

class annotation {
  final Testing test;
  const annotation(this.test);
}

void main() {
   @annotation(new Testing("Annotation instanciation"))  var a = "hello";

   print(a);
   var annot = new annotation(new Testing("Local instanciation"));
   print(a);
}

此代码结果:

  

$ hello

     

$ Local instanciation

     

$ hello

因此从未调用过注释构造函数。

将来可能会添加此功能

信息: 实际上,它在这种情况下不起作用,因为它是一个局部变量声明。 对于函数,类或其他函数,它将起作用。

答案 1 :(得分:2)

不,这是不可能的。

您是正确的,您需要使用镜像来检索元数据。规范说:

"Metadata can be retrieved at runtime via a reflective call, provided the annotated
 program construct p is accessible via reflection."

但是,局部变量(在函数体内声明的变量)没有镜像,因此无法通过反射访问它。

您只能找到顶级,类成员或函数参数(以及技术上的本地函数声明,但不能很好地工作)的声明镜像。 / p>

答案 2 :(得分:1)

通过使用currentMirrorSystem().findLibrary,我可以检索库中的声明列表。使用new Symbol('')表示当前未命名的库,并且可以访问全局标识符。我也可以得到main方法,但我无法访问main中的内部变量。所以答案是肯定的。

但是,我想知道ClosureMirror是否值得一看。

答案 3 :(得分:1)

据我所知,目前只支持类或顶级字段的字段,但在运行时反映时,方法/函数内的局部变量不支持。 也许源镜像有更多功能(我还没有使用它)但我认为这只能在编译时使用。