As Matthew Flaschen commented answered, you'll need to have a "manifest file" in your jar, and that should contain Main-Class
header pointing out which is the main class in the jar to execute. The answer by aioobe perfectly illustrates the simplest way to do this.
But instead of doing that always "manually", I'd recommend that you take a look at a build tool, such as Apache Ant (or Maven, but that's probably a bit harder to get started with), which are very commonly used to automate these kind of build sequences.
With Ant, you'd create a "buildfile" (most commonly named build.xml
) like this:
<project name="Tester">
<target name="build"
description="Compiles the code and packages it in a jar.">
<javac srcdir="src" destdir="classes" source="1.6" target="1.6"/>
<jar destfile="Tester.jar">
<fileset dir="classes"/>
<manifest>
<attribute name="Main-Class" value="com.example.Tester"/>
</manifest>
</jar>
</target>
</project>
Now, calling ant build
would compile your code and package it in "Tester.jar", which will also contain the correct type of manifest header, so that you can run it with java -jar Tester.jar
. (Note that this example assumes that your sources are in "src" directory, relative to where you run the command. You'll also need to have Ant installed of course.)
If you do decide to try out Ant, its official manual will be immensely useful (especially the list of Ant "tasks" which e.g. shows what options you can give to specific tasks like javac
or jar
).