7

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.

nvalada
  • 265
  • 1
  • 11
  • where is an option to give 10 upvotes :) such a great question and answer, exactly what I needed. Curious to know more about your work related to this. – Vipin May 13 '22 at 19:30

1 Answers1

8

Please try adding annotation this way:

    TypeSpec spec = TypeSpec.classBuilder("SomeResource")
            .addAnnotation(
                    AnnotationSpec.builder(RequestMapping.class)
                    .addMember("value", "$S", "/api")
                    .build())
            .build();
rpozarickij
  • 1,477
  • 3
  • 14
  • 27