Creating a custom AbstractProcessor and integrating with Eclipse

Viewed 15228

I'm trying to create a new annotation with which I'll do some runtime wiring, but, for a number of reasons, I'd like to verify at compile time that my wiring will be successful with some rudimentary checks.

Suppose I create a new annotation:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation{
}

Now I want to do some kind of validation at compile time, like check the field that CustomAnnotation annotates is of a particular type: ParticularType. I'm working in Java 6, so I created an 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;
    }

}

Then, based on some instructions I found, I created a folder META-INF/services and created a file javax.annotation.processing.Processor with contents:

 com.example.CompileTimeAnnotationProcessor

Then, I exported the project as a jar.

In another project, I built a simple test class:

public class TestClass {
    @CustomAnnotation
    private String bar; // not `ParticularType`
}

I configured the Eclipse project properties as follows:

  • Set Java Compiler -> Annotation Processing: "Enable annotation processing" and "Enable processing in editor"
  • Set Java Compiler -> Annotation Processing -> Factory Path to include my exported jar and checked under advanced that my fully qualified class shows up.

I clicked "apply" and Eclipse prompts to rebuild the project, I hit okay -- but no error is thrown, despite having the annotation processor.

Where did I go wrong?


I ran this using javac as

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

with output

@CustomAnnotation annotated fields must be of type ParticularType

1 Answers
Related