Search code examples
dartannotationsmetadata

How can I get the metadata of a top-level function in Dart


import 'dart:mirrors';
const Tag = 'tag';
@Tag
void func() => print("hello");
class A {
  @Tag
  void func() => print("hello");
}
main() {
  // top-level func
  print(reflect(func).type.metadata);
  //method
  print(reflectClass(A).declarations[Symbol('func')].metadata.first.reflectee);
}
// output
//[]
//tag

The metadata of the top-level function is empty. But the method in the Class can access its metadata. Is there any way to get the metadata of the top-level function?


Solution

  • import 'dart:mirrors';
    
    const Tag = 'tag';
    @Tag
    void func() => print("hello");
    
    class A {
      @Tag
      void func() => print("hello");
    }
    
    main() {
      var mirrors = currentMirrorSystem();
      // top-level func
      var f = mirrors.isolate.rootLibrary.declarations[#func];
      print(f.metadata.first.reflectee);
      //method
      print(reflectClass(A).declarations[Symbol('func')].metadata.first.reflectee);
      // Closure on `func` has no metadate
      print(reflect(func).type.metadata);  
    }
    

    Result

    tag
    tag
    []