Use local jar as a dependency in my Gradle Java project

故事扮演 提交于 2020-05-26 10:52:11

问题


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

回答1:


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



回答2:


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.




回答3:


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



回答4:


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.*;


来源:https://stackoverflow.com/questions/58034975/use-local-jar-as-a-dependency-in-my-gradle-java-project

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!