Search code examples
javacode-generationjavapoet

Annotation Code Gen with JavaPoet


I am writing a code generator using JavaPoet and need to put an annotation on a class

For example :

@RequestMapping("/api")
public class SomeResource {
   // rest of the code elided
}

I am able to get this far:

TypeSpec spec = TypeSpec
   .classBuilder("SomeResource")
     .addAnnotation(AnnotationSpec.builder(RequestMapping.class)
     // what should go here?
     .build())
   .build();

There is an addMember method in the AnnotationSpec.Builder but that does not appear to do what I want.


Solution

  • Please try adding annotation this way:

        TypeSpec spec = TypeSpec.classBuilder("SomeResource")
                .addAnnotation(
                        AnnotationSpec.builder(RequestMapping.class)
                        .addMember("value", "$S", "/api")
                        .build())
                .build();