【发布时间】:2012-05-18 22:12:12
【问题描述】:
对于下面的自定义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-from-annotations-in-an-annotationprocessor/
Update2:你可以通过做得到MyApplication.class
String classname = ((TypeElement)e).getQualifiedName().toString();
【问题讨论】:
标签: java annotations