3

Look at the following code snippet.

import "dart:mirrors";

class meta {
    final String data;

    const meta(this.data);
}


@meta("Tag")
doSomething() => print("You have to do something");

void main() {
    doSomething();
}

How can I retrieve functions, that is market with metadata tags? In my example, I want to find out, which method is marked with meta tags.

Cœur
  • 37,241
  • 25
  • 195
  • 267
softshipper
  • 32,463
  • 51
  • 192
  • 400
  • Take a look at https://bitbucket.org/andersmholmgren/constraint/src/cb1bf16e2355a98ebc55a429f951aff198476918/lib/src/runtime_constraint_resolver.dart?at=master for code that does that – Anders Oct 28 '14 at 08:54

2 Answers2

3

you could do something like this:

void main() {
    doSomething();
    getMetaData();
}

void getMetaData() {
  LibraryMirror currentLib = currentMirrorSystem().libraries.values.last;
  currentLib.declarations.forEach((Symbol s, DeclarationMirror mirror) {
    if(mirror.metadata.length > 0) {
      print('Symbol $s has MetaData: "${mirror.metadata.first.reflectee.data}"');
    }
  });
}

This should give you:

You have to do something
Symbol Symbol("doSomething") has MetaData: "Tag"

You could also analyze your files from another project and use dart:mirrors on that file instead of inspecting the current library. Maybe libraries.values.last will not always return the current library - so you might need to change it. In my case it worked.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Robert
  • 5,484
  • 1
  • 22
  • 35
2
var decls = currentMirrorSystem().isolate.rootLibrary.declarations;
print(decls.keys.where((k) => decls[k] is MethodMirror && 
    decls[k].metadata.where((k) => k.reflectee is meta).isNotEmpty));

see also How can i test the existence of a function in Dart?

Community
  • 1
  • 1
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567