Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Java library file with IntelliJ IDEA

I'm trying to create a library which could be used in other projects. I've written one class with several static methods to do some stuff. I wanted to try it out but I am not able to use the imported JAR file.

I have compiled my code as an artifact and took the JAR file from "out" folder and then copied it to another project. After that I went to "Project structure", tab "Libraries" and I pressed the plus button. I've found the JAR file and selected it, afterwards IDEA asked me to specify dependencies so I did, but when I want to use it in code I am not able to do so. It can't even be imported.

Class from library not recognized

Any ideas why it ignores my library? Thanks!

What should I do in order to create a JAR library with IntelliJ IDEA, that is usable in other projects?

like image 284
Dropout Avatar asked Aug 18 '13 15:08

Dropout


2 Answers

You are running into a very common dependency management problem.

IMO the real answer is to use a build system like Maven, Ant, or Gradle (I'd go Gradle myself). What you are trying to do is manual, hard to reproduce, and brittle.

Every time you make a change you will have to go through manual steps to create a new JAR. And you really don't understand your dependencies.

To go all out with best practices you would be to have real build system that publishes to a continuous integration server, which compiles and runs tests. On successful completion of the tests, the JARs are published to an artifact server (Nexus/Artifactory).

The people you are sharing with would consume the JARs via the build system by declaring dependencies on your JAR.

like image 129
phil swenson Avatar answered Oct 15 '22 02:10

phil swenson


I figured out what my problem was. When I created the library I was trying to make it simple. Too simple, unfortunately. I had a package with a class in it that was compiled into a JAR. Structure shown below:

foo
 |
 |_ MyLib.java 

However in order to use classes from a created JAR library they have to be placed in packages. That means if I have:

foo
 |
 |_bar
 |  |
 |  |_MyInnerLib.java
 |
 |_MyOuterLib.java

I am able to import and use methods from MyInnerLib but MyOuterLib isn't reachable nor importable. This was the error I was making.

like image 29
Dropout Avatar answered Oct 15 '22 02:10

Dropout