以前版本的dart能够使用
cm.getters.values
如在此答案中张贴的:https://stackoverflow.com/a/14505025/2117440
但是,实际功能已被删除,并以替换为特色
cm.declarations.values
最后的代码获取所有属性, getter , setter ,方法和构造函数。我想知道是否有一种方法可以只获取“ getter 和属性”而没有其他方法。
我现在正在使用的代码是:
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}');
});
}
正如您在前面的代码中看到的,要检查是否不是构造函数,我需要将
declaration.simpleName
与cm.simpleName
进行比较。直到我了解效率低下,因为我们正在比较字符串。总之,我想知道是否存在或将有更好的方法来解决此问题。
最佳答案
也许有更好的方法,但这应该可以提供您所需要的
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}');
}
});
转换为
VariableMirror
或MethodMirror
后,您可以获得更多属性:字段:
-isConst
-isFinal
-isStatic
方法:
-builderName
-isConstructor
-isConstConstructor
-isFactoryConstructor
-isGenerativeConstructor
-isGetter
-isOperator
-isRedirectingConstructor
-isRegularMethod
-isSetter
-isStatic
-isSynthetic
关于dart - 使用Dart中的反射从ClassMirror获取 setter/getter 和/或属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22317924/