根据规范,元数据可以出现在变量声明之前。
但是,它没有说明是否可以检索。
const annotation = null;
main() {
@annotation
var a = "";
print(reflect(a) is DeclarationMirror);
}
输出false
;
是否可以检索这种注释用法?
根据规范,元数据可以出现在变量声明之前。
但是,它没有说明是否可以检索。
const annotation = null;
main() {
@annotation
var a = "";
print(reflect(a) is DeclarationMirror);
}
输出false
;
是否可以检索这种注释用法?
不,这是不可能的。
您需要使用镜像来检索元数据是正确的。规范说:
"Metadata can be retrieved at runtime via a reflective call, provided the annotated
program construct p is accessible via reflection."
但是,局部变量(在函数体内声明的变量)没有镜像,因此它完全不能通过反射访问。
您只能为顶级声明、类成员或函数参数(从技术上讲,是局部函数声明,但效果不佳)找到镜像。
对不起,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);
}
此代码结果:
$你好
$ 本地实例化
$你好
所以注解构造函数从未被调用过。
可能将来会添加此功能
信息: 实际上,在这种情况下它不起作用,因为它是一个局部变量声明。对于函数、类或其他函数,它会起作用。
通过使用currentMirrorSystem().findLibrary
,我可以检索库中的声明列表。通过使用new Symbol('')
来表示当前未命名的库,并且可以访问全局标识符。我也可以得到这个main
方法,但是我无法访问 main 中的内部变量。所以答案是部分肯定的。
但是,我想知道是否ClosureMirror
值得一看。
据我所知,目前仅支持类的字段或顶级字段,但不支持在运行时反映的方法/函数内的局部变量。也许源镜像有更多的功能(我还没有使用它)但我认为这只能在编译时使用。