使用 JavaPoet 生成注解
Generating annotations using JavaPoet
我正在使用 JavaPoet 编写代码生成器,需要在 class
上添加注释
例如:
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()
此代码生成 class 但生成的代码缺少 CacheConcurrencyStrategy 的导入语句。
如何生成代码以便输出所有需要的代码?
试试这个:
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
标识枚举 class,$L
标识枚举常量。
我正在使用 JavaPoet 编写代码生成器,需要在 class
上添加注释例如:
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()
此代码生成 class 但生成的代码缺少 CacheConcurrencyStrategy 的导入语句。 如何生成代码以便输出所有需要的代码?
试试这个:
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
标识枚举 class,$L
标识枚举常量。