dart - 如何使用 Dart 的 Mirrors API 获取对象的所有字段(包括其父类(super class))?

标签 dart dart-mirrors

给定两个 Dart 类,例如:

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

class B extends A {
  double d;
}

并给出一个 B 的实例:

var b = new B();

如何获取 b 中的所有字段实例,包括来自其父类(super class)的字段?

最佳答案

使用 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;
  }
}

关于dart - 如何使用 Dart 的 Mirrors API 获取对象的所有字段(包括其父类(super class))?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28444437/

相关文章:

dart - 反射(reflect)非进口类

flutter - 如何在 flutter 中创建无限网格?

dart - 如何通过镜像 API 获取静态方法的具体对象?

dart - 通过元数据标签引用类

dart - 如何在Dart应用程序中播放音频

dart - 如何使用反射(镜像)访问 Dart 类中的方法名称?

dart - JS中的Dart Mirrors: '_ListConstructorSentinel'类型不是 'int'类型的子类型

firebase - 如何在 Flutter 中基于 Future 结果构建 Stream?

firebase - Flutter:Stream已经被监听了

dart - 如何访问 angular.dart 组件的属性或方法