这真的是在Dart中获取注释的simpleName
的唯一方法吗?
// Annotate with this class to enable reflection.
class Reflector extends Reflectable {
const Reflector()
: super(
invokingCapability,metadataCapability
);
}
const reflector = const Reflector();
// Reflector for annotation
class MetaReflector extends Reflectable {
const MetaReflector()
: super(metadataCapability);
}
const metareflector = const MetaReflector();
@metareflector
class MyAnnotation {
final String name;
const MyAnnotation(this.name);
}
@reflector // This annotation enables reflection on A.
class A {
final int a;
A(this.a);
int valueFunction() => a;
int get value => a;
@MyAnnotation("James Bond")
String nameFunction() => "Mike";
}
最后一行返回SimpleName-似乎有点复杂?
test('> Annotation', () {
final A a = new A(10);
final InstanceMirror im = reflector.reflect(a);
final ClassMirror cm = im.type;
Map<String, MethodMirror> instanceMembers = cm.instanceMembers;
expect(instanceMembers.keys.contains("valueFunction"),isTrue);
expect(instanceMembers.keys.contains("value"),isTrue);
expect(instanceMembers.keys.contains("nameFunction"),isTrue);
final MethodMirror mm = instanceMembers["nameFunction"];
expect(mm.isRegularMethod,isTrue);
expect(mm.metadata.length,1);
final x = mm.metadata.first;
expect(x,new isInstanceOf<MyAnnotation>());
expect((x as MyAnnotation).name,"James Bond");
final InstanceMirror imAnnotation = metareflector.reflect(x);
final ClassMirror cmAnnotation = imAnnotation.type;
expect(cmAnnotation.simpleName,"MyAnnotation");
}); // end of 'Annotation' test
最佳答案
在测试expect(x,new isInstanceOf<MyAnnotation>());
时,您实际上已使计算结果变得微不足道:静态已知MyAnnotation
实例的类的名称是"MyAnnotation"
。
但是,如果您的实际使用情况不是静态地致力于注释的类型,那么您将需要一种更加动态的方法。获得元数据对象的类镜像(如您所愿)是可行的常规方法,并且您还需要metaReflector
之类的东西才能获得查找该类镜像的支持。顺便说一句,我不明白为什么您需要在metadataCapability
上使用metaReflector
,但是我希望它需要一个typeCapability
。
请注意,可反射的最新版本需要declarationsCapability
才能使用instanceMembers
和staticMembers
(在没有该功能的情况下支持它们是不正常的)。
如果可以使事情变得更加静态,那么可以选择一些中间解决方案:您可以将元数据组织到子类型层次结构中,以便需要处理的元数据类型的每个实例都具有nameOfClass
方法,或者您可以创建一个Map<Type, String>
,将您将处理的每种元数据类型转换为名称,或者甚至可以(请原谅;-)使用toString()
,它将显示其类未覆盖toString()
中的Object
的任何对象的名称。
最后,如果您要以“某种动态”方式处理元数据,我建议您考虑直接使用Type
值:您可以查找x.runtimeType
并根据与MyAnnotation
的比较来制定决策,就像做出决策一样根据与字符串"MyAnnotation"
的比较,仅当您要进行文本操作(例如“名称与该正则表达式匹配的任何类都将在此处执行”)时,您才能通过字符串获得任何 yield 。
(应该说runtimeType
有点昂贵,因为它会导致在运行时保留额外的数据,尤其是dart2js,但是在使用可反射时已经需要这些数据)。
关于dart - 具有可反射lib的DartLang中的注释的simpleName,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34405820/