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

怎甘沉沦 提交于 2020-01-06 01:58:26

问题


Previous version of dart were 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 featuread and replaced by

cm.declarations.values

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

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 previous code to check if is not the constructor I need to compare the declaration.simpleName with cm.simpleName. Which 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.


回答1:


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



来源:https://stackoverflow.com/questions/22317924/obtain-getters-and-or-attribuites-from-classmirror-using-reflection-in-dart

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!