Search code examples
dartdart-mirrors

Dart: How to convert variable identifier names to strings only for variables of a certain type


Using Dart here.

As the above title suggests, I have a class (shown below) that has three bool instance variables. What I want to do is create a function that inspects the identifier names of these instance variables and prints each of them out in a string. The .declarations getter that comes with the ClassMirror class ALMOST does this, except it also gives me the name of the Constructor and any other methods I have in the class. This is no good. So really what I want is a way to filter by type (i.e., only give me the boolean identifiers as strings.) Any way to do this?

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

    }

  }

}

OUTPUT IS: isMarried isBoard2 isBoard3 boolsToStrings BooleanHolder


Solution

  • Sample code.

    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;
    }
    

    Output:

    bool1
    bool2
    int1
    int2