Search code examples
dartdart-mirrors

How do I get all the fields of an object (including its superclass), using Dart's Mirrors API?


Given two Dart classes like:

class A {
  String s;
  int i;
  bool b;
}

class B extends A {
  double d;
}

And given an instance of B:

var b = new B();

How do I get all the fields in the b instance, including fields from its superclass?


Solution

  • Use dart:mirrors!

    import 'dart:mirrors';
    
    class A {
      String s;
      int i;
      bool b;
    }
    
    class B extends A {
      double d;
    }
    
    main() {
      var b = new B();
    
      // reflect on the instance
      var instanceMirror = reflect(b);
    
      var type = instanceMirror.type;
    
      // type will be null for Object's superclass
      while (type != null) {
        // if you only care about public fields,
        // check if d.isPrivate != true
        print(type.declarations.values.where((d) => d is VariableMirror));
        type = type.superclass;
      }
    }