我来这里问完全相同的问题。 ...,并找到了拉尔夫(Ralph)发布的相同博客链接。
这是一篇很长的文章,但是非常丰富。 故事的摘要-有两种处理方法,一种是简单的方法,另一种是“更正确的”方法。
这是简单的方法:
private static TypeMirror getMyValue1(MyAnnotation annotation) {
try
{
annotation.myValue(); // this should throw
}
catch( MirroredTypeException mte )
{
return mte.getTypeMirror();
}
return null; // can this ever happen ??
}
另一种较单调的方式(无例外):
private static AnnotationMirror getAnnotationMirror(TypeElement typeElement, Class> clazz) {
String clazzName = clazz.getName();
for(AnnotationMirror m : typeElement.getAnnotationMirrors()) {
if(m.getAnnotationType().toString().equals(clazzName)) {
return m;
}
}
return null;
}
private static AnnotationValue getAnnotationValue(AnnotationMirror annotationMirror, String key) {
for(Entry extends ExecutableElement, ? extends AnnotationValue> entry : annotationMirror.getElementValues().entrySet() ) {
if(entry.getKey().getSimpleName().toString().equals(key)) {
return entry.getValue();
}
}
return null;
}
public TypeMirror getMyValue2(TypeElement foo) {
AnnotationMirror am = getAnnotationMirror(foo, MyAnnotation.class);
if(am == null) {
return null;
}
AnnotationValue av = getAnnotationValue(am, "myValue");
if(av == null) {
return null;
} else {
return (TypeMirror)av.getValue();
}
}
当然,一旦获得TypeMirror,您(至少以我的经验)几乎总是想要TypeElement:
private TypeElement asTypeElement(TypeMirror typeMirror) {
Types TypeUtils = this.processingEnv.getTypeUtils();
return (TypeElement)TypeUtils.asElement(typeMirror);
}
...最后一点不明显的地方使我花了一个小时的时间才拔掉头发,然后才第一次整理出来。 这些注释处理器实际上一点也不难编写,API刚开始时非常令人困惑,而且冗长。 我很想推出一个使所有基本操作都显而易见的帮助程序类,但这是另一天的故事(如果需要的话,请告诉我)。