Java AnnotationProcessor源代码

时间:2012-04-09 14:28:46

标签: java annotations

任何人都可以向我提供一个简单的java注释处理器的代码片段,只需在调用其进程方法时打印“foo”。我已经在这工作了2天,但我还没有达到目标

这是我的代码:


public class ComplexityProcessor extends AbstractProcessor {

    public ComplexityProcessor() {
        super();
    }

    @Override
    public boolean process(Set annotations,
                           RoundEnvironment roundEnv) {
        String message = "annotation found in ";
        processingEnv.getMessager().printMessage(javax.tools.Diagnostic.Kind.NOTE, message);

        try {
            JavaFileObject jfo = processingEnv.getFiler().createSourceFile("Foo");
            BufferedWriter bw = new BufferedWriter(jfo.openWriter());
            bw.append("Bar!!!");
            bw.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        for (Element elem : roundEnv.getElementsAnnotatedWith(Complexity.class)) {
            Complexity complexity = elem.getAnnotation(Complexity.class);
            message = "annotation found in " + elem.getSimpleName()
                           + " with complexity " + complexity.value();
            processingEnv.getMessager().printMessage(javax.tools.Diagnostic.Kind.NOTE, message);
            try {
                JavaFileObject jfo = processingEnv.getFiler().createSourceFile("Foo");
                BufferedWriter bw = new BufferedWriter(jfo.openWriter());
                bw.append("Bar!!!");
                bw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        return true; // no further processing of this annotation type
    }

1 个答案:

答案 0 :(得分:2)

我发现了答案

那么你对未来的需求:

  1. 带有注释处理器和任何提及的注释的jar,这样您就不会遇到类路径问题
  2. META-INF / services / processor文件中的文本文件,带有处理器类的名称。这也在我的处理器
  3. 上面的jar中
  4. 使用javac -processor参数进行编译。这就是我正在寻找的,我最初使用的3或4个教程中没有提到