如何使用 Dart 的 Mirrors API 获取对象(包括其超类)的所有字段?

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

给定两个 Dart 类 喜欢:

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

class B extends A {
  double d;
}

并给出 B 的实例:

var b = new B();

如何获取 b 实例中的所有字段,包括其超类中的字段?

使用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;
  }
}
import 'dart:mirrors';

class Test {
    int a = 5;
    static int s = 5;
    final int _b = 6;
    int get b => _b;
    int get c => 0;
}

void main() {

    Test t = new Test();
    InstanceMirror instance_mirror = reflect(t);
    var class_mirror = instance_mirror.type;

    for (var v in class_mirror.declarations.values) {

        var name = MirrorSystem.getName(v.simpleName);

        if (v is VariableMirror) {
            print("Variable: $name => S: ${v.isStatic}, P: ${v.isPrivate}, F: ${v.isFinal}, C: ${v.isConst}");
    } else if (v is MethodMirror) {
        print("Method: $name => S: ${v.isStatic}, P: ${v.isPrivate}, A: ${v.isAbstract}");
    }

    }
}