Annotation Code Gen with JavaPoet
Asked Answered
E

1

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.

Enfranchise answered 1/9, 2015 at 10:20 Comment(1)
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.Lingulate
M
8

Please try adding annotation this way:

    TypeSpec spec = TypeSpec.classBuilder("SomeResource")
            .addAnnotation(
                    AnnotationSpec.builder(RequestMapping.class)
                    .addMember("value", "$S", "/api")
                    .build())
            .build();
Milla answered 1/9, 2015 at 10:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.