Getting value of a class variable through mirrorin

2019-08-03 07:53发布

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条回答
仙女界的扛把子
2楼-- · 2019-08-03 08:23

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).

查看更多
登录 后发表回答