我想在 dart 的对象中获取私有变量。
这个变量没有吸气剂,所以我想通过反射来做到这一点。
我尝试了很多方法,但对我来说没有任何作用。
例如,当我这样做时:
var reflection = reflect(this);
InstanceMirror field = reflection.getField(new Symbol(fieldName));
我收到错误:
fieldName 没有 getter。
这是正常的,因为变量没有 getter。
我怎样才能得到这个变量?
使用测试代码编辑:
这是我的反射测试(测试变量是 ReflectClass(MyClass))
reflectClass(Injector).declarations.keys.forEach((e) => test.getField(e, test.type.owner))
我收到此错误:
类“_LocalInstanceMirror”没有实例方法“getField”
匹配参数。
如果我这样做:
reflectClass(Injector).declarations.keys.forEach((e) => test.getField(e))
I get:
类“DynamicInjector”没有实例 getter
'_PRIMITIVE_TYPES@0x1b5a3f8d'。
声明的值也是如此。
您收到的错误消息实际上是正确的。该类有一个针对该字段的 getter。
Dart 隐式地为所有字段创建 getter 并为所有非最终/非常量字段创建 setter。
Dart2JS 似乎尚不支持访问私有成员。
看https://code.google.com/p/dart/issues/detail?id=13881 https://code.google.com/p/dart/issues/detail?id=13881
下面是如何访问私有字段的示例:
(示例来自https://code.google.com/p/dart/issues/detail?id=16773 https://code.google.com/p/dart/issues/detail?id=16773)
import 'dart:mirrors';
class ClassWithPrivateField {
String _privateField;
}
void main() {
ClassMirror classM = reflectClass(ClassWithPrivateField);
Symbol privateFieldSymbol;
Symbol constructorSymbol;
for (DeclarationMirror declaration in classM.declarations.values) {
if (declaration is VariableMirror) {
privateFieldSymbol = declaration.simpleName;
} else if (declaration is MethodMirror && declaration.isConstructor) {
constructorSymbol = declaration.constructorName;
}
}
// it is not necessary to create the instance using reflection to be able to
// access its members with reflection
InstanceMirror instance = classM.newInstance(constructorSymbol, []);
// var s = new Symbol('_privateField'); // doesn't work for private fields
// to create a symbol for a private field you need the library
// if the class is in the main library
// var s = MirrorSystem.getSymbol('_privateField', currentMirrorSystem().isolate.rootLibrary);
// or simpler
// var s = MirrorSystem.getSymbol('_privateField', instance.type.owner);
for (var i=0; i<1000; ++i) {
instance.setField(privateFieldSymbol, 'test');
print('Iteration ${instance.getField(privateFieldSymbol)}');
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)