Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 308
nvalada Avatar asked Aug 25 '15 03:08

nvalada


1 Answers

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.

like image 185
Jesse Wilson Avatar answered Oct 20 '22 20:10

Jesse Wilson