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

Set*_*add 5 dart dart-mirrors

给定两个 Dart 类,例如:

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

class B extends A {
  double d;
}
Run Code Online (Sandbox Code Playgroud)

并给出一个实例B

var b = new B();
Run Code Online (Sandbox Code Playgroud)

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

Set*_*add 4

使用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;
  }
}
Run Code Online (Sandbox Code Playgroud)