给定两个 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实例中的所有字段,包括其超类中的字段?
使用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)
| 归档时间: |
|
| 查看次数: |
865 次 |
| 最近记录: |