使用反射来检查类中的集合

时间:2014-12-29 14:53:58

标签: dart dart-mirrors

我的代码看起来像这样:

Zoo myZoo;

class Zoo {
  Park<Duck> ducks;
  Park<Lama> lamas;
}

class Park<E extends Animal> {
  ...
}

我需要从Zoo的ClassMirror知道它们有多少Park以及它们包含什么样的Animal子类型。实际上我需要在这个例子中检索Duck和Lama TypeMirrors。

到目前为止,我已经能够通过解析字符串来打印出来,但我无法实际检索到类型。

1 个答案:

答案 0 :(得分:1)

我的问题并不完全清楚,但我想这就是你要找的东西

void main() {
  ClassMirror cm = reflectClass(Zoo);
  cm.declarations.forEach((k, v) {
    if(v is VariableMirror) {
      if ((v as VariableMirror).type.typeArguments.where((t) => t.isSubtypeOf(reflectType(Animal))).length > 0) {
        print('$k, $v');
      }
    }
  });
}
相关问题