我有一个kotlin项目,我正在使用来自xsd的Jaxb生成的src文件。这些生成的源的问题是它们有nullable
字段,但IDEA不知道。这可能会导致production
中的错误。为了解决这个问题,我们可以将@Nullable
注释添加到生成的srs中的所有getter中。
我们怎样才能优雅地做到这一点?
我制定了这个解决方案,它对我有效,但也许有人知道更好的方法?
渐变kt任务
tasks.register("nullableForXsdFields") {
group = "code generation"
description = "Add Nullable annotation to generated jaxb files"
actions.add {
val xjcFiles = fileTree("$buildDir/generated-sources/main/xjc")
xjcFiles.forEach { xjcFile ->
var content = xjcFile.readText()
Regex("(public) (\w+|<|>|\*) (get)").findAll(content).distinct()
.forEach { match ->
content = content.replace(
match.groups[0]!!.value,
match.groups[0]!!.value.replace("public ", "public @Nullable ")
)
}.run {
content = content.replace(
"import javax.xml.bind.annotation.XmlType;",
"import javax.xml.bind.annotation.XmlType;nimport org.jetbrains.annotations.Nullable;"
)
}
xjcFile.writeBytes(content.toByteArray())
}
}
}
tasks.getByName("xjcGeneration").finalizedBy("nullableForXsdFields")
tasks.getByName("compileKotlin").dependsOn("nullableForXsdFields")
tasks.getByName("compileJava").dependsOn("nullableForXsdFields")
xjcGeneration
-是我从xsd 生成src的插件
我遇到了同样的问题,所以我为mavenjaxb插件创建了一个扩展com.github.labai:labai-jsr305-jaxb-plugin
。
默认情况下,此扩展将所有生成的包标记为可为null的,然后使用@NotNull仅标记那些xsd方案强制要求的字段。
您可以在github中找到如何与maven一起使用它的更多详细信息https://github.com/labai/labai-jsr305