Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a java class with a jar in the classpath?

Tags:

java

classpath

So, I can do this very well:

java mypackage.MyClass

if ./mypackage/MyClass.class exists. I can also happily do this:

java -cp myjar.jar mypackage.MyClass

if the class file exists in the appropriate part of the jar. Easy stuff. But I can't for the life of me manage to do something like this:

java -cp utilities.jar mypackage.MyClass

where ./mypackage/MyClass.class exists, and where ./utilities.jar exists (not containing MyClass, of course).

Am I about to feel stupid?

like image 960
amara Avatar asked Jun 20 '11 09:06

amara


People also ask

How do I run a class from a jar?

To run a Runnable jar you can use java -jar fileName. jar or java -jar -classpath abc. jar fileName.

How do I run a Java program in classpath?

Setting Classpath from Command LineUse set CLASSPATH command initially, and then run Java application or tool in the same command line window. “ It will search the classes/resources in mentioned classpath locations. Classpath entries that are neither directories nor archives (.


2 Answers

Possibly :)

# On Unix java -cp utilities.jar:. mypackage.MyClass  # On Windows java -cp utilities.jar;. mypackage.MyClass 

Basically that's just including . (the current directory) on the classpath as well as the jar file.

like image 57
Jon Skeet Avatar answered Oct 05 '22 10:10

Jon Skeet


Try this if you're on Windows:

java -cp .;utilities.jar mypackage.MyClass 

Or this if you're on Linux:

java -cp .:utilities.jar mypackage.MyClass 

The current directory is not in the CLASSPATH by default when you specify a value for -cp.

like image 41
duffymo Avatar answered Oct 05 '22 12:10

duffymo