How can I specify dependencies in the manifest fil

2019-02-19 01:22发布

问题:

I generated .class files by the following command:

javac -cp \directoryName\external.jar myPackageDirectory\First.java myPackageDirectory\Second.java

I needed to use -cp during compilation and name of .jar file of an "external" library (external.jar) to be able to use this library from my code.


Using my .class files I have generated my .jar file in the following way:

jar cfm app.jar manifest.txt myPackageDirectory\*.class

manifest.txt contains just one line:

Main-Class: myPackageName.First

My problem is that I am not sure that I will be able to run my .jar file on other computers. I think so because during the compilation I specified the location of the .jar file of the external library. So, my .class files (included into the .jar file will try to find the .jar file of the external library in a specific directory and there is no guaranty that that the .jar file of the external library will be in the same directory as on the my computer.


I heard that the above problem can be solved by a

usage of a MANIFEST file that I include in my own jar, and which will list dependency locations

but I do not understand how it works. I do need to specify location of the "external.jar" at the compilation stage (otherwise the compiler complains).

回答1:

First of all: you don't seem to compile a class called MainClass and all your .java files seem to be in a package, so I assume that MainClass is just a placeholder and you actually use the correct class name here.

You need to specify a Class-Path header that mentions your external .jar to your manifest.txt and deliver the .jar file together with your jar. You need to do this in addition to specifying the -cp at compile time.



回答2:

Further to what Joachim Sauer (very correctly) says, there is a way to pack your dependency jars into the same jar as your own code. The programs that accomplish this create a super-main class and manipulate the classpath to find the dependent jars in your resulting jar.

Several programs can do this; one of them is called OneJar.