13

I have a Dart class that is annotated with metadata:

class Awesome {
  final String msg;
  const Awesome(this.msg);

  String toString() => msg;
}

@Awesome('it works!')
class Cool {

}

I want to see if Cool was annotated, and if so, with what. How do I do that?

Seth Ladd
  • 77,313
  • 56
  • 165
  • 258

1 Answers1

12

Use the dart:mirrors library to access metadata annotations.

import 'dart:mirrors';

class Awesome {
  final String msg;
  const Awesome(this.msg);

  String toString() => msg;
}

@Awesome('it works!')
class Cool {

}

void main() {
  ClassMirror classMirror = reflectClass(Cool);
  List<InstanceMirror> metadata = classMirror.metadata;
  var obj = metadata.first.reflectee;
  print(obj); // it works!
}

To learn more, read about the ClassMirror#metadata method.

Pixel Elephant
  • 17,447
  • 5
  • 62
  • 79
Seth Ladd
  • 77,313
  • 56
  • 165
  • 258