I have a local jar file named mylib.jar
. I want to used it as a dependency in my Gradle Java project.
This is what I tried:
I created a libs/
folder under project root. I put the jar file under libs/
folder.
MyProject
->libs/mylib.jar
->build.gradle
->src/...
In my build.gradle:
apply plugin: 'java-library'
group 'com.my.app'
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
flatDir {
dirs 'libs'
}
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
api files('libs/mylib.jar')
}
But I can't access the public classes defined in mylib.jar
in my project code. Why?
===== More information =====
The content of my jar:
mylib.jar
> com.my.jar.package
>ClassFromJar.class
Here is how I use the jar:
// Compilation error: Cannot resolve symobl 'ClassFromJar'
import com.my.jar.package.ClassFromJar;
public class MyEntryPoint {
// Compilation error: Cannot resolve symbol 'ClassFromJar'
ClassFromJar instance = new ClassFromJar();
}
The Jar is created under the $project/build/libs/ folder.
Gradle declares dependencies on JAR files inside your project's module_name /libs/ directory (because Gradle reads paths relative to the build.gradle file). This declares a dependency on version 12.3 of the "app-magic" library, inside the "com.example.android" namespace group.
Similar answers suggesting
Add next to your module gradle (Not the app gradle file):
repositories { flatDir { dirs 'libs' } }
dependencies { implementation files('libs/mylib.jar') }
compile fileTree
:compile fileTree(dir: 'libs', include: 'mylib.jar')
A flatDir
repository is only required for *.aar
(which is an Android specific library format, completely irrelevant to the given context). implementation
and api
affect the visibility, but these are also Android DSL specific). In a common Java module, it can be referenced alike this:
dependencies {
compile fileTree(include: ["*.jar"], dir: "libs")
}
And make sure to drop the *.jar
into the correct one libs
directory, inside the module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With