Run class in Jar file
To run a Java class in a JAR, use this command:
Remember, this ClassWithMain
is the one containing the public static void main(String[] args)
. Conversely, in an executable JAR configured with a Main-Class
in the manifest, employ the -jar
option:
Key detail: com.package.ClassWithMain
is the fully qualified class name—it includes the package. The JAR should be executable, and hold a Main-Class
line in its manifest.
Invoking from a different directory
If your current directory isn't the same as your JAR's location, double-check your classpath:
-
On Unix/Linux:
-
In a Windows setup:
Always replace /absolute/path/to/
or C:\absolute\path\to\
with your JAR file location's actual path.
Naming conventions are here to help
Adhere to naming conventions: classes are happier in distinct packages, not in the default one. This prevents potential mess-up when loading classes in different environments. Also, the names of your classes should ideally not overlap with Java's standard library or other common libraries. Good naming will save your day!
System properties and common pitfalls
The -D
option allows you to inject system properties:
For error hunting, inspect class and JAR names for typos, and verify your JAR's manifest has Main-Class
configured properly.
Using manifest for executable JARs
Building an executable JAR needs a manifest file with the entry: Main-Class
. When your manifest plays ball, the -jar
flag makes your program execution a breeze:
Verify the manifest's Main-Class
to assure smooth execution.
Advanced classpath setting
With complex classpath requirements, specifying multiple JARs or directories is common. Use path separator (':' for Unix/Linux and ';' for Windows) appropriately:
Opting for different classpath notations
You can replace -cp
with -classpath
. It's all about comfort with your shell environment or personal style:
Debugging classpath with verbose
option
If there are issues like missing or misconfigured Main-Class
, typographical errors, or incorrect classpath, then -verbose:class
is your detective:
Was this article helpful?