Search code examples
javacode-generationjavapoet

Generating annotations using JavaPoet


I am writing a code generator using JavaPoet and need to put an annotation on the class

For example :

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 looks like this:

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 the class but the resulting code is missing the import statement for the CacheConcurrencyStrategy. How can I generate the code so that all the required code is outputted?


Solution

  • Try this:

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

    The $T identifies the enum class and the $L the enum constant.