Compile a local jar file with Gradle

In this tutorial we will compile a local jar file with Gradle into our java project.

Technologies used:
gradle 2.14.1
Java SE 1.8

For this tutorial you can go clone the repo from github and just delete the build.gradle file from the project and build it from scratch along with me.

Step 1:
Take a look at the project structure. Notice that we are using the src/main/java convention to set up our project.
Gradle and many other build tools expect this structure so we will be using it. We could use a different project structure
but then we would have to help Gradle out a bit by specifying that structure using something called the sourceset.

Step 2:

Take a look at the folder and notice that it has two dependencies in it. will require the jar in the lib folder and the Math class in the utility package.

Step 3:

Now lets make our build.gradle file. Create a file called build.gradle in the root of your project directory.
Now run the command gradle tasks like so

This command gives us the basic tasks avaialble with gradle when we first install it. We can extend gradle by using plugins though. So in your build.gradle file add

Now when we run the gradle tasks command again we can see that more tasks are available to us. These new tasks will make it easy to build our java project.


We need to add a line to our build.gradle file to tell it to include the local jar in the jar we are about to build. This will give us a “fat” jar. A fat jar is just a jar that has all the dependencies it needs to run. It can stand on its own. Also we need to add a line to tell java where the main method of our jar file will be so it knows where to start the program at. This is designated in a manifest file. Add this to your build.gradle.

Now lets add one more line to our build.gradle file. This line tells gradle to look in the lib directory for local jars.
Add the line below to your build.gradle.

Now run

build and you will get a Jar file that is ready to run. It will be located in the build/libs directory.
Run the command below and see the output!

Now we have a build script that can take care alot of the task we had to do manually when building our project using the java and javac CLI tools. Gradle may not seem like a huge help here but as projects get bigger and more complex it becomes a must!


Add a Comment

Your email address will not be published. Required fields are marked *