对于以下自定义 Java 注解
@CustomAnnotation(clazz=SomeClass.class)
public class MyApplicationCode
{
...
}
我基本上希望能够在编译时同时获取 MyApplicationCode 的 Class 对象和 clazz 参数,以确认一些编码约定的一致性(另一个故事)。基本上我希望能够访问注释处理器中的 MyApplicationCode.class 和 Someclass.class 代码。我快到了,但我错过了一些东西。我有
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.SOURCE)
public @interface CustomAnnotation
{
public Class clazz();
}
然后我有处理器:
public class CustomAnnotationProcessor extends AbstractProcessor
{
private ProcessingEnvironment processingEnvironment;
@Override
public synchronized void init(ProcessingEnvironment processingEnvironment)
{
this.processingEnvironment = processingEnvironment;
}
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment environment)
{
Set<? extends Element> elements = environment.getElementsAnnotatedWith(ActionCommand.class);
for(Element e : elements)
{
Annotation annotation = e.getAnnotation(CustomAnnotation.class);
Class clazz = ((CustomAnnotation)annotation).clazz();
// How do I get the actual CustomAnnotation clazz?
// When I try to do clazz.getName() I get the following ERROR:
// Attempt to access Class object for TypeMirror SomeClass
// Also, how do I get the Class object for the class that has the annotation within it?
// In other words, how do I get MyApplicationCode.class?
}
}
}
所以我在 process 方法中尝试做的是从下面的原始代码中获取 SomeClass.class 和 MyApplication.class 在编译时进行一些自定义验证。我似乎无法终生弄清楚如何获得这两个值......
@CustomAnnotation(clazz=SomeClass.class)
public class MyApplicationCode
更新:以下帖子有更多细节,而且更接近。但问题是你最终仍然得到一个 TypeMirror 对象,从中提取类对象,它没有解释:http ://blog.retep.org/2009/02/13/getting-class-values -来自注释处理器中的注释/
Update2:您可以通过执行获取 MyApplication.class
String classname = ((TypeElement)e).getQualifiedName().toString();