Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get JavaPoet to generate a class literal?

Tags:

java

javapoet

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?

like image 441
Jorn Avatar asked Oct 18 '22 02:10

Jorn


1 Answers

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();
like image 114
David Pérez Cabrera Avatar answered Oct 21 '22 04:10

David Pérez Cabrera