How to retrieve metadata using dart:mirror in Dartlang

Wednesday, October 16, 2013

Dartlang provides Metadata feature, which is similar to Annotations in Java(

Dartlang tutorial introduces package:meta and its two members, @deprecated and @overrides (package:meta also provides @proxy).

DartEditor recognise the metadata as shown at above tutorial. The tutorial also explains how to create custom metadata and retrieve it. But there is no code sample on how to retrieve it, so I'm curious about the way.

Through reading some implementations such as @published metadata in Polymer.dart, I find the way. Actually It's easy once I understand the use of dart:mirrors.

Here is the sample code. Pretty simple and easy to read, isn't it?

import 'dart:mirrors';

class todo {
  final String who;
  final String what;

  const todo(this.who, this.what);

@todo('akira', 'add something')
class Foo {
  @todo('naoto', 'do something')
  String fooVariable = 'a';

  @todo('kitano', 'change the name')
  void fooMethod() {


void main() {
  InstanceMirror im = reflect(new Foo());
  ClassMirror classMirror = im.type;
  // ClassMirror
  classMirror.metadata.forEach((metadata) {
    print(metadata.reflectee.who); // -> akira
    print(metadata.reflectee.what); // -> add something

  // VariableMirror   
  for (VariableMirror variable in classMirror.variables.values) {
    print(variable.metadata.first.reflectee.who); // -> naoto
    print(variable.metadata.first.reflectee.what); // -> do something

  // MethodMirror
  classMirror.methods.values.forEach((MethodMirror method) {
    print(method.metadata.first.reflectee.who); // -> kitano
    print(method.metadata.first.reflectee.what); // -> change the name


  1. Thank you. Found it interesting and useful. Java is a general purpose, high-level, class-based and object-oriented programming language. And we provide Java course in Chennai at Fita.

  2. Thanks for sharing the post.. parents are worlds best person in each lives of individual..they need or must succeed to sustain needs of the family. recover deleted files from USB