Jordanss10
Jordanss10

Reputation: 4121

How external libraries work

I'm just to get my head around how external libraries work in java. Everywhere I look things are unclear.

Normally, i understand using a external library involves settings a classpath to the desired class, JAR, etc.

My question is how (if I were to build my project into a JAR) would it be able to access the library if it were, to say, be used on another computer? Would the external JAR be included in MY JAR file? Otherwise, how would it be able to access the external JAR?

Example would be how this works with bukkit plugins, how does the plugin know where to reference the bukkit.jar file?

Upvotes: 3

Views: 1774

Answers (2)

Daniel Kaplan
Daniel Kaplan

Reputation: 67300

Every jar has a manifest file. In there you can refer to other jars outside the jar. These will be included in your classpath. You can see how to do that here. As an example, you can put this into your manifest file:

Class-Path: jar1-name jar2-name directory-name/jar3-name

As you can see here, it uses relative paths. If they were absolute paths, they would say something like C:\...\jar1-name. Using relative paths means, as long as the jars stay in this same place relative to the main jar, this code will run correctly.

Alternatively, you can provide a script that runs a java command and includes all the jars you need on the classpath.

And for another alternative, you can use something called uberjar which will put all these things together into one jar and then you can just distribute that.

And for another alternative, you can use a jar classloader that will load classes from embedded jars.


For education's sake, you might want to check out my answer here that describes a lot of ways to distribute java applications.

Upvotes: 2

BlackHatSamurai
BlackHatSamurai

Reputation: 23483

.Jar files are nothing more that extra lines of code, or complete programs. If you want to include them, you have to add them to the build path and/or the project. Once they are added, you can reference them and use them.

If you were to create a .Jar file or library, everything you used would be included. When you add a library, it is added to the project, and thus, when you release the project, it is included in your program.

Upvotes: 0

Related Questions