Create annotations using JavaPoet

I am writing a code generator using JavaPoet and you need to put the annotation in a class

For instance:

package some.package import org.hibernate.annotations.CacheConcurrencyStrategy; import javax.persistence.Entity; import javax.persistence.Cache @Entity @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class SomeClass { } 

My code is as follows:

 TypeSpec spec = TypeSpec .classBuilder("SomeClass") .addAnnotation(Entity.class) .addAnnotation(AnnotationSpec.builder(Cache.class) .addMember("usage", "$L", CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) .build()) .build() 

This code generates a class, but the import code for the CacheConcurrencyStrategy is missing in the resulting code. How can I generate code to output all the necessary code?

+6
source share
1 answer

Try the following:

 TypeSpec spec = TypeSpec .classBuilder("SomeClass") .addAnnotation(Entity.class) .addAnnotation(AnnotationSpec.builder(Cache.class) .addMember("usage", "$T.$L", CacheConcurrencyStrategy.class, CacheConcurrencyStrategy.NONSTRICT_READ_WRITE.name()) .build()) .build() 

$T identifies an enumeration class and $L enumeration constant.

+8
source

All Articles