Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use local jar as a dependency in my Gradle Java project

Tags:

java

gradle

jar

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();
}
like image 796
Leem.fin Avatar asked Sep 20 '19 20:09

Leem.fin


People also ask

Where are jars in Gradle project?

The Jar is created under the $project/build/libs/ folder.

Where are Gradle dependency jars?

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.


2 Answers

Similar answers suggesting

  1. Local dir

Add next to your module gradle (Not the app gradle file):

repositories {
   flatDir {
       dirs 'libs'
   }
}
  1. Relative path:
dependencies {
    implementation files('libs/mylib.jar')
}
  1. Use compile fileTree:
compile fileTree(dir: 'libs', include: 'mylib.jar')
like image 95
user7294900 Avatar answered Oct 15 '22 06:10

user7294900


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.

like image 34
Martin Zeitler Avatar answered Oct 15 '22 05:10

Martin Zeitler