Table of Contents
Introduction
Here in this example I am going to tell you how to include non-classpath jars in gradle based Java project. You may need to include non-classpath jar files in order to make your application run. Non-classpath jars are those jar files which are not included in your classpath through dependency or dependencies in build.gradle script. So, these jar files are not listed under Project and External Dependencies of your project.
Your non-classpath jars need to be included in the build.gradle script under dependencies {…}
block. You need to mention which folder the Gradle build tool has to look up for fetching the jars for building the project.
A FileTree a hierarchy of files. It extends FileCollection
to add hierarchy query and manipulation methods. You typically use a FileTree
to represent files to copy or the contents of an archive.
You can obtain a FileTree
instance using Project.fileTree(java.util.Map)
, Project.zipTree(Object)
or Project.tarTree(Object)
.
The order of the files in a FileTree
is not stable, even on a single computer.
Prerequisites
Java 1.8+, Gradle 5.6.1+
Include Non-classpath Jars in Gradle Script
I am using fileTree()
to load the non-class path jar files in Gradle script. Let’s assume that the jar file(s) is/are kept under lib folder of the project. So, the jar file is actually placed under <project root directory>/lib folder. Therefore, the following fileTree()
function will load the jar files from the lib directory. The build.script should look similar to the following content:
…
dependencies {
…
compile fileTree(dir: ‘lib’, include: [‘*.jar’])
…
}
…
Or you can also use implementation as shown below:
…
dependencies {
…
implementation fileTree(dir: ‘lib’, include: [‘*.jar’])
…
}
The *.jar
indicates that all files that end in .jar
will be loaded from the lib folder. If you want to include a single jar file you can put the exact name of the file. Even you can specify multiple jar files separated by comma. But when you want to load all jar files and not bother about file names then you can use wildcard pattern (*.jar) for jar file names.
That’s all and hope you got an idea how to include jar files which are not available in the project’s classpath.