[英]Invoke top level function with dart:mirrors
I'm struggling with how to invoke a top level function in dart.我正在努力解决如何在 dart 中调用顶级 function。 I'd like to be able to annotate a function with @Route
, find all the Route
annotations, then check that the annotation is on a method, and then call that method by its symbol.我希望能够使用 @Route 注释@Route
,找到所有Route
注释,然后检查注释是否在方法上,然后通过其符号调用该方法。
What I have so far is:到目前为止,我所拥有的是:
class Route {
final String url;
const Route(this.url);
}
@Route('/')
void handle() {
print('Request received');
}
void main() {
var mirrorSystem = currentMirrorSystem();
var lm = mirrorSystem.isolate.rootLibrary;
for (var mirror in lm.declarations.values) {
var metadata = mirror.metadata;
for (var im in metadata) {
if (im.reflectee is Route) {
print('Route found');
// how to invoke the function handle associated with the route annotation?
}
}
}
}
From this point i'm not sure how I would then call the method.从这一点来看,我不确定我将如何调用该方法。 If it was a class then I could use invoke
and pass in the Symbol
for the method, but that doesn't work as it's not a class.如果它是 class,那么我可以使用invoke
并传入方法的Symbol
,但这不起作用,因为它不是 class。
Can anyone give me some clues?谁能给我一些线索? Information about the mirrors library in dart is fairly sparse unfortunately.不幸的是,关于 dart 中镜像库的信息相当稀少。
I worked this out.我解决了这个问题。 For anyone who finds this, you use the LibraryMirror
on rootLibrary
to invoke the top level function:对于发现此问题的任何人,您可以使用rootLibrary
上的LibraryMirror
来调用顶级 function:
void main() {
var mirrorSystem = currentMirrorSystem();
var lm = mirrorSystem.isolate.rootLibrary;
for (var mirror in lm.declarations.values) {
var metadata = mirror.metadata;
for (var im in metadata) {
if (im.reflectee is Route && mirror is MethodMirror) {
lm.invoke(mirror.simpleName, []);
// prints 'Request received'
}
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.