5

I want to use JavaPoet to generate an annotation with a type literal as value. For example:

@AutoService(MyService.class)
public class GeneratedClass implements MyService {
}

I've tried all the options I can think of, but none work:

TypeSpec.classBuilder("GeneratedClass")
    .addModifiers(Modifier.PUBLIC)
    .addSuperinterface(MyService.class)
    .addAnnotation(
        AnnotationSpec.builder(AutoService.class).addMember(
            "value", "$L", MyService.class
        ).build()
    )

using $L generates interface MyService

using $T generates my.package.MyService, which is close but misses the .class part.

using $N gives an error: expected name but was my.package.MyService

how do I get it to generate MyService.class as the annotation value?

Nicolas Filotto
  • 39,066
  • 11
  • 82
  • 105
Jorn
  • 16,599
  • 15
  • 67
  • 103

1 Answers1

3

Did you try this?

TypeSpec.classBuilder("GeneratedClass")
            .addModifiers(Modifier.PUBLIC)
            .addSuperinterface(MyService.class)
            .addAnnotation(
                    AnnotationSpec.builder(AutoService.class).addMember(
                    "value", "$T.class", MyService.class).build()
            ).build();
Jorn
  • 16,599
  • 15
  • 67
  • 103
David Pérez Cabrera
  • 4,594
  • 2
  • 20
  • 35