KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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
Tags (comma-separated)
Save Edits
Cancel