dartdart-mirrors

Obtain getters and/or attributes from ClassMirror using reflection in Dart?


The previous version of dart was able to get getters using

cm.getters.values

As is posted in this answer: https://stackoverflow.com/a/14505025/2117440

However actual version was removed that featured and replaced by

cm.declarations.values

The last code gets all attributes, getters, setters, methods, and constructors. I would like to know if there is a way to get only "getters and attributes" without other methods.

The code that I'm using right now is that one:

import "dart:mirrors";

class MyNestedClass {
  String name;
}
class MyClass {
  int i, j;
  MyNestedClass myNestedClass;
  int sum() => i + j;

  MyClass(this.i, this.j);
}

void main() {
  MyClass myClass = new MyClass(3, 5)
    ..myNestedClass = (new MyNestedClass()..name = "luis");
  print(myClass.toString());
  InstanceMirror im = reflect(myClass);

  ClassMirror cm = im.type;

  Map<Symbol, MethodMirror> instanceMembers = cm.instanceMembers;

  cm.declarations.forEach((name, declaration) {
      if(declaration.simpleName != cm.simpleName) // If is not te constructor
        print('${MirrorSystem.getName(name)}:${im.getField(name).reflectee}');
  });
}

As you can see in the previous code to check if is not the constructor I need to compare the declaration.simpleName with cm.simpleName. Until I understand is inefficient since we are comparing strings.

In conclusion, I would like to know if there is or will be a better way to solve this problem.


Solution

  • Maybe there is a better way but this should provide what you need

      cm.declarations.forEach((name, declaration) {
        VariableMirror field;
        if(declaration is VariableMirror) field = declaration;
    
        MethodMirror method;
        if(declaration is MethodMirror) method = declaration;
    
        if(field != null) {
          print('field: ${field.simpleName}');
        } else if(method != null && !method.isConstructor){
          print('method: ${method.simpleName}');
        }
      });
    

    After casting to VariableMirror or MethodMirror you can get a lot more properties:

    field:
    - isConst
    - isFinal
    - isStatic

    method:
    - constructorName
    - isConstructor
    - isConstConstructor
    - isFactoryConstructor
    - isGenerativeConstructor
    - isGetter
    - isOperator
    - isRedirectingConstructor
    - isRegularMethod
    - isSetter
    - isStatic
    - isSynthetic