CacheConcurrencyStrategy

CacheConcurrencyStrategy

我正在使用JavaPoet编写代码生成器,并且需要在类上添加注释

例如 :

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 {
}

我的代码如下所示:
TypeSpec spec = TypeSpec
  .classBuilder("SomeClass")
  .addAnnotation(Entity.class)
  .addAnnotation(AnnotationSpec.builder(Cache.class)
     .addMember("usage", "$L", CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
     .build())
  .build()

这段代码生成了该类,但是结果代码缺少CacheConcurrencyStrategy的import语句。
如何生成代码,以便输出所有必需的代码?

最佳答案

试试这个:

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标识枚举类,$L标识枚举常量。

10-08 20:16