简体   繁体   中英

Use local jar as a dependency in my Gradle Java project

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();
}

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')

I thinks you should use in dependency declaration compile name: 'mylib' in this case flatDir will search for mylib.jar.

You could try following build.gradle (it works in my project):

plugins {
    id 'java'
}
apply plugin: 'java-library'

group 'dependency'
version '1.0-SNAPSHOT'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
    flatDir {
        dirs 'libs'
    }
}

dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.12'
    compile  name: 'mylib'
}

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.

Just in case:

1 - compiler must have access to lib directory and jar example:

javac -cp .;lib\* *.java

2 - ALSO import must be mentioned in java file example in your java add

import static org.lwjgl.glfw.GLFW.*;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM