gpt4 book ai didi

java - 如何在 Java 或 Kotlin 中使用我自己的注释包装 @Column 注释

转载 作者:行者123 更新时间:2023-12-03 09:35:22 27 4
gpt4 key购买 nike

我只是想拥有自己的注释来清理注释质量,并在需要时轻松更改它们;

import javax.persistence.Column
import javax.validation.constraints.Size
class Foo(){
@Column(name="bar_", nullable = false, length = 32)
@Size(min = 32, max = 32)
String bar;

@Column(nullable = false, length = 32)
@Size(min = 32, max = 32)
String bas;

@Column(nullable = false, length = 32, unique=true)
@Size(min = 32, max = 32)
String baq;
}
希望我能
class Foo(){
@MyColumn(name="bar_")
String bar;

@MyColumn
String bas;

@MyColumn(unique=true)
String baq;
}
nullable = false, length = 32是默认参数。
欢迎使用 Java 或 Kotlin 解决方案。

最佳答案

由于您使用的是从 javax 导入的第 3 方注释。最好的选择是引入复合注释。 (Kotlin doesn't support 注释继承。

@Column(name = "bar_", nullable = false, length = 32)
@Size(min = 32, max = 32)
annotation class Anno
Spring Boot 在将大量配置注释组合在一起时做得非常好 - check it out .
复合注解有问题 Anno ,寿。您必须提供具有常量值的注释参数。
如果你确定,你需要一个参数化的注释,比如
@Column(...)
@Size(min = Anno.max, max = Anno.min)
annotation class Anno(val min: Int, val max: Int)
看看 Kapt或 Kotlin Compiler 插件,您将需要一段代码生成。
使用 Kapt 或 Kotlin 编译器插件,您只需覆盖 newField您的自定义方法 ClassBuilder :
  override fun newField(
origin: JvmDeclarationOrigin,
access: Int,
name: String,
desc: String,
signature: String?,
value: Any?
): FieldVisitor {
// if field is annotated with Anno -- add two custom annotation with parameters of your choice
// otherwise perform a standard field init
}
然后注册它
class AnnoRegister : ComponentRegistrar {
override fun registerProjectComponents(
project: MockProject,
configuration: CompilerConfiguration
) {
...
}
将此处理集成到现有的 gradle 或 maven 项目中应该相对容易,或者只是传递给 kotlinc .

关于java - 如何在 Java 或 Kotlin 中使用我自己的注释包装 @Column 注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65037923/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com