使用Dart中的反射从ClassMirror获取吸气剂和/或属性? [英] Obtain getters and/or attributes from ClassMirror using reflection in Dart?
问题描述
以前的dart版本能够使用
The previous version of dart was able to get getters using
cm.getters.values
在此答案中发布: 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}');
});
}
如您在前面的代码中看到的,检查是否不是构造函数需要将 declaration.simpleName
与 cm.simpleName
进行比较。
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.
推荐答案
也许有更好的方法,但这应该可以满足您的需求
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}');
}
});
转换为 VariableMirror
或<$ c之后$ c> MethodMirror 您可以获得更多属性:
After casting to VariableMirror
or MethodMirror
you can get a lot more properties:
字段:
-isConst
-isFinal
-isStatic
field:
- isConst
- isFinal
- isStatic
方法:
-构造函数名称
-isConstructor
-isConstConstructor
-isFactoryConstructor
-isGenerativeConstructor
-isGetter
-isOperator
-isRedirectingConstructor
-isRegularMethod
-isSetter
-isStatic
-isSynthetic
method:
- constructorName
- isConstructor
- isConstConstructor
- isFactoryConstructor
- isGenerativeConstructor
- isGetter
- isOperator
- isRedirectingConstructor
- isRegularMethod
- isSetter
- isStatic
- isSynthetic
这篇关于使用Dart中的反射从ClassMirror获取吸气剂和/或属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!