Compile classes from generated-resources before java compilation

Thanks to this xsd-plugin, I’m able to generate .java classes from a provided list of .xsd files. The classes are generated to build/generated-sources/**.*.java. However, to be able to use them in the code, I would like to compile those .java classes to .class files and store them in build/classes/**.*.class

What is the recommended Gradle way to execute a javac command after the plugin’s task called xjc but before the ‘final’ compilation with the java plugin (in the build task)?

I use Gradle 2.13 if that’s important.

1 Like

You want to add these generated sources to a sourceSet and let the conventional tasks (created when a sourceSet is added) handle the compilation. One way to do this is just to add the generated sources to the main sourceSet. Assuming you have a task type that exposes the generated sources directory:

task generateSources(type: GenerateSources) {
    outputDir = file("${buildDir}/generated-sources")
    ...
}

sourceSets {
    main.java.srcDirs generateSources.outputDir
}

// Make sure that source generation occurs before compilation
tasks.withType(JavaCompile) {
    dependsOn tasks.withType(GenerateSources)
}

On the other hand, you can add it to a new sourceSet:

task generateSources(type: GenerateSources) {
    outputDir = file("${buildDir}/generated-sources")
    ...
}

sourceSets {
    generated {
        java.srcDirs generateSources.outputDir
    }

    // set up a dependency for the main sourceSet on the generated sourceSet
    main.compileClasspath += generated.output
}

// Make sure that source generation occurs before compilation
tasks.withType(JavaCompile) {
    dependsOn tasks.withType(GenerateSources)
}

Which to use depends on what your requirements are. Just adding to main is simpler and involves fewer tasks, but adding a new sourceset gives you more flexibility around what classpath is used for the compilation of generated sources as well as more fine-grained incremental build checking.

2 Likes

@Gary_Hale, thanks for your code snippets. I adapted your code and made some adjustments as the plugin has its own task (called xjc) and I couldn’t find a way to figure out whether it’s of type ‘GenerateSources’ or not.

This code in build.gradle works for me:

buildscript {
    ext {
        generatedSources = "${buildDir}/generated-sources/"
        resourcesPath = 'src/main/resources/'
    }
}

sourceSets {
    main.java.srcDirs "${generatedSources}/xjc"
}

tasks.withType(JavaCompile) {
    dependsOn xjc
}

jaxb {
    xsdDir = resourcesPath
}

Unless you have any further concerns, I would consider this question answered.

Thanks again and cheers

1 Like