【发布时间】:2011-10-04 22:22:35
【问题描述】:
我正在尝试创建一个新的注释,我将使用它来进行一些运行时接线,但是,出于多种原因,我想在编译时通过一些基本检查来验证我的接线是否成功。
假设我创建了一个新注解:
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation{
}
现在我想在编译时进行某种验证,例如检查CustomAnnotation 注释的字段是否属于特定类型:ParticularType。我正在使用 Java 6,所以我创建了一个 AbstractProcessor:
@SupportedAnnotationTypes("com.example.CustomAnnotation")
public class CompileTimeAnnotationProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations,
RoundEnvironment roundEnv) {
Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(CustomAnnotation.class);
for(Element e : elements){
if(!e.getClass().equals(ParticularType.class)){
processingEnv.getMessager().printMessage(Kind.ERROR,
"@CustomAnnotation annotated fields must be of type ParticularType");
}
}
return true;
}
}
然后,根据我找到的一些说明,我创建了一个文件夹 META-INF/services 并创建了一个文件 javax.annotation.processing.Processor,内容如下:
com.example.CompileTimeAnnotationProcessor
然后,我将项目导出为 jar。
在另一个项目中,我构建了一个简单的测试类:
public class TestClass {
@CustomAnnotation
private String bar; // not `ParticularType`
}
我将 Eclipse 项目属性配置如下:
- 设置 Java 编译器 -> 注释处理:“启用注释处理”和“在编辑器中启用处理”
- 设置 Java 编译器 -> 注释处理 -> 工厂路径以包含我导出的 jar 并在高级下检查我的完全合格的类是否显示。
我点击了“应用”,Eclipse 提示重建项目,我点击了 OK ——但没有抛出错误,尽管有注释处理器。
我哪里做错了?
我使用javac as 运行了这个
javac -classpath "..\bin;path\to\tools.jar" -processorpath ..\bin -processor com.example.CompileTimeAnnotationProcessor com\test\TestClass.java
有输出
@CustomAnnotation 注解的字段必须是 ParticularType 类型
【问题讨论】:
-
首先,注释处理器是否可以在 Eclipse 之外与 javac 一起使用?
-
@antlersoft:是的,它可以在 Eclipse 之外直接使用 javac(编辑反映了这一点)。
-
您是否检查过 Eclipse 中的错误日志(窗口 > 显示视图 > 错误日志以防您看不到它)?当注释处理器失败时,您可能不会收到带有错误的弹出对话框,但您会在错误日志中显示错误。您还可以尝试在 Eclipse 中调试处理器,方法是在处理器中使用带有 kind=NOTE 的 Messager.printMessage(),因为这些也会显示在错误日志中。
-
您构建的注释处理器 JAR 中是否包含 ParicularType 和 CustomAnnotation 类?如果没有,当处理器实际在 Eclipse 中运行时,您可能会收到 NoClassDefFoundErrors。
-
@prunge:事实上,错误确实出现在错误日志中,有没有办法让错误更高?比如说,在类编辑器视图中或至少在“问题”窗格中?
标签: java eclipse annotations