Java 创建自定义抽象处理器并与Eclipse集成

Java 创建自定义抽象处理器并与Eclipse集成,java,eclipse,annotations,Java,Eclipse,Annotations,我正在尝试创建一个新的注释,我将使用它进行一些运行时连接,但是,出于一些原因,我希望在编译时通过一些基本检查来验证我的连接是否成功 假设我创建了一个新注释: @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface CustomAnnotation{ } 现在我想在编译时进行某种验证,比如检查CustomAnnotationannotations属于特定类型的字段:specialtype。我

我正在尝试创建一个新的注释,我将使用它进行一些运行时连接,但是,出于一些原因,我希望在编译时通过一些基本检查来验证我的连接是否成功

假设我创建了一个新注释:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation{
}
现在我想在编译时进行某种验证,比如检查
CustomAnnotation
annotations属于特定类型的字段:
specialtype
。我在Java 6中工作,所以我创建了一个
抽象处理器

@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;
    }

}
然后,我将项目导出为jar

在另一个项目中,我构建了一个简单的测试类:

public class TestClass {
    @CustomAnnotation
    private String bar; // not `ParticularType`
}
我将Eclipse项目属性配置如下:

  • 设置Java编译器->注释处理:“启用注释处理”和“在编辑器中启用处理”
  • 将Java编译器->注释处理->工厂路径设置为包含导出的jar,并在“高级”下检查是否显示完全限定的类
我单击“apply”并在Eclipse提示下重建项目,我点击OK——但是没有抛出错误,尽管有注释处理器

我哪里出错了


我使用
javac
作为

javac -classpath "..\bin;path\to\tools.jar" -processorpath ..\bin -processor com.example.CompileTimeAnnotationProcessor com\test\TestClass.java
有输出

@CustomAnnotation注释字段的类型必须为SpecialType


要在编辑器中显示错误,需要在
printMessage
函数中标记导致错误的
元素。对于上面的示例,这意味着编译时检查应使用:

processingEnv.getMessager().printMessage(Kind.ERROR,
    "@CustomAnnotation annotated fields must be of type ParticularType",
    e); // note we explicitly pass the element "e" as the location of the error

首先,注释处理器是否在Eclipse之外使用javac?@antlersoft:是的,它在Eclipse之外使用纯javac(编辑反映了这一点)。您是否检查了Eclipse中的错误日志(窗口>显示视图>错误日志,以防看不到)?当注释处理器出现故障时,可能不会出现带有错误的弹出对话框,但会在错误日志中显示错误。您还可以尝试在Eclipse中调试处理器,方法是在处理器中添加Messager.printMessage()和kind=NOTE,正如错误日志中显示的那样。您构建的注释处理器JAR中是否包含ParicularType和CustomAnnotation类?如果不是,当处理器在Eclipse中实际运行时,您可能会收到NoClassDefFoundErrors。@prunge:事实上,错误确实会显示在错误日志中,是否有方法将错误提高到更高的级别?比如说,在类编辑器视图中,或者至少在“问题”窗格中,我花了一段时间才弄清楚,作为未来观众的注意事项,作者的“processingEnv.getMessager().printMessage”()与被投票为正确解决方案的第三个参数“e”之间的区别已通过。感谢您的解决方案。我本来打算将注释处理器扔进/bin,但现在它工作得很好!
processingEnv.getMessager().printMessage(Kind.ERROR,
    "@CustomAnnotation annotated fields must be of type ParticularType",
    e); // note we explicitly pass the element "e" as the location of the error