Search code examples
dartdart-mirrors

How do I get the type of a property of a class in Dart using mirrors?


Given I have this class

class Animal {

    int age;

}

and that I have a String that contains "age".

How do I get the field type int from either a ClassMirror or an InstanceMirror?


Solution

  •   // get ClassMirror
    
      // either from instance
      var a = new Animal();
      InstanceMirror im = reflect(a);
      ClassMirror cm = im.type;
    
      // or from type
      ClassMirror cm = reflectClass(Animal);
    
      // get type info of the field from ClassMirror
      VariableMirror vm = cm.declarations[#age]; // or cm.declaration[new Symbol('age')];
      print(vm.type.qualifiedName);
      print(vm.type.simpleName);