Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 808
corgrath Avatar asked Dec 11 '25 06:12

corgrath


1 Answers

  // 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);
like image 146
Günter Zöchbauer Avatar answered Dec 14 '25 05:12

Günter Zöchbauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!