How external libraries work

北战南征 提交于 2019-12-10 10:26:58

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/17118356/how-external-libraries-work

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