I can link a .jar on compile time but not on run time

I compile java from the command line.

I can run:

javac test.java -cp jarfile.jar

Now i thought i could run (from the same folder)

java test -cp jarfile.jar

I also tried

java test

and

java test -cp jarfile

I get a java.lang.NoClassDefFoundError

Is there any conceptual mistake? Can I assume the Code is correct as I can compile it?

Jon Skeet
people
quotationmark

The first problem is that you're specifying the class name before the classpath - so it thinks that -cp is one of the command line arguments to your class, rather than an argument to the JVM to say where to find classes.

The second problem - potentially - is that you're not including the current directory in the classpath. You want:

java -cp jarfile.jar;. test

(on Windows) or

java -cp jarfile.jar:. test

(on Unix)

If you don't need any classes other than the ones in the jar file, of course, you just need:

java -cp jarfile.jar test

Or if you've included an appropriate manifest in your jar file, you can just use:

java -jar jarfile.jar

people

See more on this question at Stackoverflow