Generating annotations using JavaPoet
Asked Answered
W

1

6

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?

Wesleywesleyan answered 25/8, 2015 at 3:29 Comment(0)
M
10

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.

Manteau answered 25/8, 2015 at 3:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.