How to get JavaPoet to generate a class literal?

I want to use JavaPoet to generate annotations with a type literal as a value. For instance:

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

I tried all the options that I can think of, but no one works:

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

using $L generates an interface MyService

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

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

How do I get it to generate MyService.class as an annotation value?

+5
source share
1 answer

Have you tried this?

 TypeSpec.classBuilder("GeneratedClass") .addModifiers(Modifier.PUBLIC) .addSuperinterface(MyService.class) .addAnnotation( AnnotationSpec.builder(AutoService.class).addMember( "value", "$T.class", MyService.class).build() ).build(); 
+2
source

All Articles