Explain Codes LogoExplain Codes Logo

How to build sources JAR with Gradle?

java
gradle
java-library-plugin
javadoc
Anton ShumikhinbyAnton Shumikhin·Dec 29, 2024
TLDR

Creating a source JAR in Gradle can be done by adding a sourcesJar task, as shown below:

task sourcesJar(type: Jar, dependsOn: classes) { classifier 'sources' from sourceSets.main.allJava }

Next, link it to your Gradle build with:

artifacts { archives sourcesJar }

In the above snippet, Gradle is configured to assemble your .java files into a sources JAR, ready to be integrated into your project's build artifacts.

Advanced Gradle 6.0+ methods

In Gradle version 6.0 and above, the java-library plugin provides a simple method to get the job done faster than a coder can grab his next cup of coffee!

java { withJavadocJar() withSourcesJar() }

This helps automate the tasks for generating Javadoc and sources JARs. Use the following to apply it:

plugins { `java-library` }

Detailed configurations

Setting task dependencies

Your source JAR may depend on other tasks. Here's how to wait in line with dependsOn:

task sourcesJar(type: Jar, dependsOn: [compileJava, processResources]) { archiveClassifier.set('sources') from sourceSets.main.allSource }

With the sourcesJar task above, compileJava and processResources won't cut in line!

Excluding specific files

Not all .java files need a VIP pass to your source JAR. To keep some out:

task sourcesJar(type: Jar) { exclude 'path/to/exclude/**' // "Sorry, you're not on the list." from sourceSets.main.allJava classifier 'sources' }

Setting up classpath for Javadoc

To ensure your Javadoc task has all necessary permissions:

javadoc.classpath += configurations.compile // "Access granted."

Testing the built source JAR

After assembling your sources JAR, test it in your IDE (like IntelliJ IDEA) to ensure it's ready for the debugging feast:

1. Open 'Project Structure' in IntelliJ. 2. Click on 'Libraries' and find your project. 3. Attach the `sources` JAR and let the debugging begin!

Special project configurations

To handle surprise ingredients in the project, check your project configurations before generating the source JARs:

task sourcesJar(type: Jar) { from sourceSets.main.allJava classifier 'sources' if (project.hasProperty('specialCase')) { from 'special/case/path' // "Adding your special sauce!" } }

Troubleshooting

Problems popping up? Double-check the classpath and archiveName, and make sure you've correctly chucked in the source directories:

task sourcesJar(type: Jar) { // ... doFirst { assert sourceSets.main.allJava.files.size() > 0 // "Oops! Your lunch box is empty!" } }