给定两个 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/