Search code examples
javajavapoet

How do I get JavaPoet to generate a class literal?


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?


Solution

  • 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();