Search code examples
gradlegradle-task

Gradle task to load files from Jar


I use vendor library to generate Java sources from an Xml. This source xml imports other xml which exists in some jar file. I know the coordinates of this Jar file. The vendor library is a blackbox to me but I know that it uses ThreadContextClassLoader to load the imports from a jar. However, it fails because it cannot find the imported xmls from the classpath/jars.

What is the gradle way of accomplishing this?

// body of gradle task
@TaskInput
void execute(IncrementalTaskInputs inputs) {
   inputs.outOfDate { changes ->
       // CodeGenerator is the vendor library
       CodeGenerator generator = new CodeGenerator();
       // call some setter methods to set the inputs.
       //
       generators.setXml(file("<path/to/the-file"))
       generator.generate();
   } 
}

Solution

  • From my other answer we have ascertained that there's no option to set the classloader for the CodeGenerator. So, the only option is to have the jar with the xml files loaded by the same classloader as the CodeGenerator`.

    Option 1: Add the jar to the buildscript classpath in a buildscript { ... } block

    buildscript {
        dependencies {
             classpath 'com.group:jar-with-xmls:1.0'
        }
    }
    

    Option 2: Add the jar to the buildscript classpath via buildSrc/build.gradle

    dependencies {
        compile 'com.vendor:code-generator:1.0'
        runtime 'com.group:jar-with-xmls:1.0'
    }