Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I execute Two different Classes from same jar file?

Tags:

java

jar

I have a project where in one package I have made Server and in Second Package I made Client. It is working fine. I want to create a Jar file. Is it possible to run Client and Server Separately from same jar file?

I have used jar file where there is only one main and when I run jar file, it automatically runs that class. Now here I will be having 2 executable classes. I want to pack them in only one jar and then want to run both from that same jar file. Is it possible? Any Suggestions, links will be of great help.

like image 864
Tara Singh Avatar asked Nov 30 '10 01:11

Tara Singh


People also ask

Can a jar have two main classes?

Jar files can contain only one Main-Class attribute in the manifest, which means a jar can contain only one mainClassName.

Can we compare 2 jar files?

Jarcomp is a comparison tool for Jar files and Zip files. It's free and cross-platform. If you have two jar files or two zip files, it will show you what the differences are in the contents. It shows which files have been added, which have been removed, and which are present in both archives.

How do I run a specific class in a jar?

To run an application in a nonexecutable JAR file, we have to use -cp option instead of -jar. We'll use the -cp option (short for classpath) to specify the JAR file that contains the class file we want to execute: java -cp jar-file-name main-class-name [args …]


2 Answers

The short answer is, YES!

The longer answer is that you can specify the class in your command line as well as putting the .jar in the classpath.

Assume two classes

A.class 
B.class

jar them into a .jar file

jar cvf AB.jar A.class B.class

run either of them

java -classpath AB.jar A
java -classpath AB.jar B
like image 174
KevinDTimm Avatar answered Sep 25 '22 23:09

KevinDTimm


Assuming both your Server and Client classes have main methods, you can execute them from the command line using the following:

java -cp jarFile.jar package1.Server

java -cp jarFile.jar package2.Client

like image 32
highlycaffeinated Avatar answered Sep 25 '22 23:09

highlycaffeinated