As a return function that is marked with metadata

Take a 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 get features that are marketable with metadata tags? In my example, I want to know which method is being tagged with meta tags.

+3


source to share


2 answers


you can 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 can also parse your files from another project and use dart: mirrors in that file instead of checking the current library. It may libraries.values.last

not always return the current library, so you may need to modify it. It worked in my case.

+3


source


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 check the existence of a function in Dart?

+2


source







All Articles