给出两个Dart类:
class A {
String s;
int i;
bool b;
}
class B extends A {
double d;
}
并给出B
的实例:
var b = new B();
如何获取b
实例中的所有字段,包括其超类中的字段?
答案 0 :(得分:3)
使用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;
}
}
答案 1 :(得分:0)
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}");
}
}
}