3

在这里使用 Dart。

正如上面的标题所暗示的,我有一个包含三个 bool 实例变量的类(如下所示)。我想要做的是创建一个函数来检查这些实例变量的标识符名称并将它们中的每一个打印在一个字符串中。ClassMirror 类 ALMOST 附带的 .declarations getter 执行此操作,除了它还为我提供了构造函数的名称和我在类中拥有的任何其他方法。这不好。所以我真正想要的是一种按类型过滤的方法(即,只给我作为字符串的布尔标识符。)有什么方法可以做到这一点?

class BooleanHolder {

  bool isMarried = false;
  bool isBoard2 = false;
  bool isBoard3 = false; 

 List<bool> boolCollection; 

  BooleanHolder() {


  }

   void boolsToStrings() {

     ClassMirror cm = reflectClass(BooleanHolder);
     Map<Symbol, DeclarationMirror> map = cm.declarations;
     for (DeclarationMirror dm in map.values) {


      print(MirrorSystem.getName(dm.simpleName));

    }

  }

}

输出是:isMarried isBoard2 isBoard3 boolsToStrings BooleanHolder

4

1 回答 1

2

示例代码。

import "dart:mirrors";

void main() {
  var type = reflectType(Foo);
  var found = filter(type, [reflectType(bool), reflectType(int)]);
  for(var element in found) {
    var name = MirrorSystem.getName(element.simpleName);
    print(name);
  }
}

List<VariableMirror> filter(TypeMirror owner, List<TypeMirror> types) {
  var result = new List<VariableMirror>();
  if (owner is ClassMirror) {
    for (var declaration in owner.declarations.values) {
      if (declaration is VariableMirror) {
        var declaredType = declaration.type;
        for (var type in types) {
          if (declaredType.isSubtypeOf(type)) {
            result.add(declaration);
          }
        }
      }
    }
  }

  return result;
}

class Foo {
  bool bool1 = true;
  bool bool2;
  int int1;
  int int2;
  String string1;
  String string2;
}

输出:

bool1
bool2
int1
int2
于 2014-04-12T05:22:06.187 回答