Invoke top level function with dart:mirrors

168 Views Asked by At

I'm struggling with how to invoke a top level function in dart. 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.

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.

Can anyone give me some clues? Information about the mirrors library in dart is fairly sparse unfortunately.

1

There are 1 best solutions below

0
On

I worked this out. For anyone who finds this, you use the LibraryMirror on rootLibrary to invoke the top level 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'
      }
    }
  }
}