1

I package all my dependency jars in the lib folder of my final jar. But when I use command to execute like java -cp my.jar MyMainClass, it said that can not load the class in the lib folder, what's wrong here ?

Thanks

zjffdu
  • 25,496
  • 45
  • 109
  • 159
  • Why is it tagged as a Maven question? What is the exact stacktrace? – Shahzeb Oct 19 '11 at 05:50
  • possible duplicate of [Classpath including JAR within a JAR](http://stackoverflow.com/questions/183292/classpath-including-jar-within-a-jar) – Jon Skeet Oct 19 '11 at 05:58

2 Answers2

1

If your program is packaged as an executable jar, you should have a separate folder where the other jar dependencies are placed, and then specify that folder as being in the classpath when you run your program:

java -classpath c:\path\to\dir_with_jars -jar myExecutableJar.jar p1.MainClass

Also: if you want to use the unorthodox method of packaging your jar dependencies inside the jar file you shuld place those dependencies at the ROOT of your executable jar, not in any folder (lib or otherwise). This way they'll effectively be at the root of your classpath, so if you run your jar as :

java -cp:. -jar myJar.jar

it should work

Note: this answer contains errors, please see the attached comments below. The idea is that there are in fact tools that let you package your jar dependencies inside the jar (as internal jars), but this will no longer work as a regular executable jar that you can run with the default JDK classloader. Instead you need a special classloaded that will take into account the internal jars. The tools which offer this functionality usually automatically add the necessary special classloaded and update the jar manifest to use it. Sorry for the mistake.

Shivan Dragon
  • 15,004
  • 9
  • 62
  • 103
  • 1
    No, it shouldn't work. -jar sets the classpath as the jar + all the *external* jar files specified in the manifest of the executable jar. If you nest jar files, you'll need a specific tool or classloader to execute the application. See http://stackoverflow.com/questions/183292/classpath-including-jar-within-a-jar – JB Nizet Oct 19 '11 at 06:44
  • Yes you are very right: when packaging the dependencies jars inside the executable jar, you need a special classloader to load those (now internal) jars. Example, when you export your project as a runnable jar with Eclipse, and you chose the option to package dependencies jars inside the jar , eclipse will also add (inside your executable jar) classes representing a special classloaded (JarRsrcLoader) and it will adda manifest which declares as main class the class of the special classloader. Sorry, I've said an incorrect thing in my answer, I will add an edit note to reflect that. – Shivan Dragon Oct 19 '11 at 09:24
0

You can also use zip to extract the archive and take a look into the my.jar to see what's in there and if your MyMain.class is there.

rit
  • 2,308
  • 3
  • 19
  • 27