我看了一下dart:mirrors库,我找到了ClassMirror。在我看到getField
时,我看不到所有字段的访问权限。不过我确实看到了getters
。
如果我想获得课程的所有字段,我是否必须通过getters
?
答案 0 :(得分:4)
不,你应该通过ClassMirror.variables
:
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.variables.values)
{
var name = MirrorSystem.getName(v.simpleName);
print("$name => S: ${v.isStatic}, P: ${v.isPrivate}, F: ${v.isFinal}");
}
}
这将输出:
_b => S: false, P: true, F: true
a => S: false, P: false, F: false
s => S: true, P: false, F: false
ClassMirror.getters
只会返回b
和c
。
答案 1 :(得分:3)
Zdeslav Vojkovic的回答有点老了。
对于Dart 1.1.3,截至2014年3月2日,这对我有用。
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}");
}
}
}
输出:
Variable: a => S: false, P: false, F: false, C: false
Variable: s => S: true, P: false, F: false, C: false
Variable: _b => S: false, P: true, F: true, C: false
Method: b => S: false, P: false, A: false
Method: c => S: false, P: false, A: false
Method: Test => S: false, P: false, A: false