问题
I am trying to understand how the Mirrors Api works. Specifically, how to obtain the value of a field from its Symbol
, using getField
.
For the getField
method, it should work for any Symbol
which is a getter, and it might be implicit. I therefore understood this that getField
could be called directly on fields. In the following code sample, the getters for a
and b
should be implictly defined.
But the code throws, complainining that it cannot find any getter.
Breaking on exception: object of NoSuchMethodError
, and breaking in 'dart:mirrors-patch_mirrors_impl.dart' on native "ClassMirror_invokeGetter";
abstract class CheckInitialized {
bool hasNull() {
var im = reflect(this);
var cm = im.type;
cm.declarations.values.where((dm) => dm is VariableMirror)
.forEach((vm) {
print(cm.getField(vm.simpleName));
});
// If field is null, return true
// If no fields are null, return false
}
}
class Test extends CheckInitialized {
int a;
String b;
}
void main() {
var a = new Test();
print(a.hasNull()); // true
}
It feels wrong to have to explicitly define a getter for this to work, but I can't see why this is not working. Of course, mirrors.dart is still very much changing, so I inlude that this is for v1.2.0.
回答1:
You are trying to run getField
on the class mirror. Since a
and b
are instance fields the getField
fails. If you change a
and b
to static
the getField
invocations will work.
Alternatively you need to invoke getField
on the instance-mirror (im
).
来源:https://stackoverflow.com/questions/22873896/getting-value-of-a-class-variable-through-mirroring-via-getfield