1

I have kotlin project where I'm using Jaxb generated src files from xsd. The problem with these generated sources is that they have nullable fields but IDEA does not know about it. It can lead to bugs in production. To fix it we can add @Nullable annotation to all getters in generated srs-es.

How can we do it gracefully?

Connor
  • 3
  • 16
lalilulelo_1986
  • 526
  • 3
  • 7
  • 18

2 Answers2

0

I made this solution, it works for me but maybe somebody knows better approuch?

Gradle kt task

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 - is my plugin to generate src from xsd

lalilulelo_1986
  • 526
  • 3
  • 7
  • 18
0

I faced the same problem, so I've created an extension for maven jaxb plugin com.github.labai:labai-jsr305-jaxb-plugin.

This extension marks all generated packages as nullable by default, and then marks with @NotNull only those fields, which are mandatory by xsd scheme.

You can find more details how to use it with maven in github https://github.com/labai/labai-jsr305

labai
  • 51
  • 1
  • 5