本文介绍了通过getField通过镜像获取类变量的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解Mirrors Api是如何工作的。具体来说,如何使用 getField 符号获取字段的值。

I am trying to understand how the Mirrors Api works. Specifically, how to obtain the value of a field from its Symbol, using getField.

对于 getField 方法,它应该适用于任何一个getter的 Symbol 它可能是隐含的。因此,我理解这可以直接在字段上调用 getField 。在下面的代码示例中, a b 的getter应该隐式定义。

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.

但是代码引发,抱怨,它找不到任何getter。
打破异常:NoSuchMethodError的对象,并在本机的dart:mirrors-patch_mirrors_impl.dart中打破ClassMirror_invokeGetter;

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
}

为此必须明确定义一个getter工作,但我不明白为什么这不工作。当然,mirrors.dart仍然有很大的变化,所以我暗示这是为v1.2.0。

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.

推荐答案

尝试在类镜像上运行 getField 。由于 a b 是实例字段,所以 getField 失败。如果您将 a b 更改为 static

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.

或者你需要调用 getField 在实例镜像( im )。

Alternatively you need to invoke getField on the instance-mirror (im).

这篇关于通过getField通过镜像获取类变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 02:42