How do I run Java .class files?
To run Java class file from the command line, the syntax is:
java -classpath /path/to/jars <packageName>.<MainClassName>
where packageName (usually starts with either com
or org
) is the folder name where your class file is present.
For example if your main class name is App and Java package name of your app is com.foo.app
, then your class file needs to be in com/foo/app
folder (separate folder for each dot), so you run your app as:
$ java com.foo.app.App
Note: $
is indicating shell prompt, ignore it when typing
If your class doesn't have any package
name defined, simply run as: java App
.
If you've any other jar dependencies, make sure you specified your classpath parameter either with -cp
/-classpath
or using CLASSPATH
variable which points to the folder with your jar/war/ear/zip/class files. So on Linux you can prefix the command with: CLASSPATH=/path/to/jars
, on Windows you need to add the folder into system variable. If not set, the user class path consists of the current directory (.
).
Practical example
Given we've created sample project using Maven as:
$ mvn archetype:generate -DgroupId=com.foo.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
and we've compiled our project by mvn compile
in our my-app/
dir, it'll generate our class file is in target/classes/com/foo/app/App.class
.
To run it, we can either specify class path via -cp
or going to it directly, check examples below:
$ find . -name "*.class"
./target/classes/com/foo/app/App.class
$ CLASSPATH=target/classes/ java com.foo.app.App
Hello World!
$ java -cp target/classes com.foo.app.App
Hello World!
$ java -classpath .:/path/to/other-jars:target/classes com.foo.app.App
Hello World!
$ cd target/classes && java com.foo.app.App
Hello World!
To double check your class and package name, you can use Java class file disassembler tool, e.g.:
$ javap target/classes/com/foo/app/App.class
Compiled from "App.java"
public class com.foo.app.App {
public com.foo.app.App();
public static void main(java.lang.String[]);
}
Note: javap
won't work if the compiled file has been obfuscated.
You need to set the classpath to find your compiled class:
java -cp C:\Users\Matt\workspace\HelloWorld2\bin HelloWorld2