Search code examples
javaintellij-ideajar

How to import(or Add) custom external JAR Library to Java project in IntelliJ ultimate


First, English is not my first language, so there are might some wired syntax in my question.

I want to follow this workflow for my programming skill.

  1. create custom Java library(JAR file)
  2. create another Java project and import custom Java library.

My problem is disappearing jar file when I use gradle-build or run static main method

anyway, I prepared some source.

  1. create custom Java library(JAR file) by Gradle docs
// src/../demo/Library
public class Library {
  // The method just for library import test
  public int add(int a, int b) {
    return a + b;
  }
}
  • after gradle build, created 'lib.jar' file in build/libs/lib.jar.
  1. create another Java project and import custom Java library
    • create very simple Java project using IntelliJ, so my project structure looks like this:
๐Ÿ“test-project
|--๐Ÿ“ src
|----๐Ÿ“ main
|------๐Ÿ“ java
|--------๐Ÿ“ org.test
|----------๐Ÿ“ LibraryTest.java 
|-- build.gradle
|-- setting.gradle
  • And I tried to import 'lib.jar' using Project Structure > Modules > + button(Add) > JARs or Directories....

So... this is result screenshot enter image description here

It looks correct, and right. 'lib.jar' is imported and LibraryTest class can using Library's method 'add(...)'. But if I run LibraryTest.main method, then lib.jar is disappear and occur build errors

.../test-project/src/main/java/org/test/LibraryTest.java:3:12
java: package demo does not exist
.../test-project/src/main/java/org/test/LibraryTest.java:9:9
java: cannot find symbol
  symbol:   class Library
  location: class org.test.LibraryTest

How can I resolve this problems...??

I tried to searching 'create java library', and I'm just expecting right result without import errors


Solution

  • IDE uses Gradle build file as initial source for project configuration. So, if dependency is missing in build file it will be removed on reload. Please add it to build file: https://www.baeldung.com/gradle-dependencies-local-jar