Thursday, June 18, 2015

Running a class from a Jar file

This post talks about executing a jar file and the jar could have one or more than one class with main method.  Remember that, you need a main method in class to be called from outside.  So if you want to run a class contained inside jar file:
Either it should have a main method or Other class have main method which calls appropriate method of your target class.

Pre-condition 
Make sure that java and jar are on your PATH. This is how you set on linux/unix systems:
export PATH=$PATH:/full_path_java_bin_directory

Otherwise, you will have to run below command from bin directory inside Java installer. I am covering here only unix/linux system (windows will be similar, though).


Running a Particular Class

$java -cp <jar_path> <className> [OPTIONAL_PARAMS]

The first argument JAR_PATH, should give the fully qualified path of the jar file. Similarly, class name should be complete. One quick way is, check out the package name of the class which you want to run. If package name is com.blogger then the class name should be com.blogger.ClassName. 

$java -cp lib/my.jar com.blogger.PostDetails   //no param
$java -cp lib/my.jar com.blogger.PostDetails postName   //main expects param with name postName
$java -cp my.jar PostDetails  //running from jar directory, and class is in default package

You can also use -classpath instead of -cp 

If the jar is executable

$java -jar <jar_path> [OPTIONAL_PARAMS]

If the jar is executable (i.e. it has manifest file inside META-INF directory and specifies the name of the class file which has main method), the command to run it is slightly different. 

$java -jar lib/my.jar

So basically we don't specify the class name in the command (as it's implicitly understood).

You can check if the jar has a manifest file by running below command:
$java -jar my.jar


--
keep coding !!!

No comments:

Post a Comment