Can I execute two different classes from the same jar file?

I have a project in which in one package I made a Server, and in the second package I made a Client. It is working fine. I want to create a jar file. Is it possible to start the client and server separately from the same jar file?

I used a jar file where there is only one main one, and when I run the jar file, it automatically runs this class. Now I will have 2 executable classes. I want to pack them in only one jar, and then I want to run both from the same jar file. Is it possible? Any suggestions, links would be very helpful.

+6
java jar
source share
2 answers

Short answer: YES!

The longer answer is that you can specify the class on the command line and also put .jar in the classpath.

Suppose two classes

A.class B.class 

Add them to the .jar file.

 jar cvf AB.jar A.class B.class 

run any of them

 java -classpath AB.jar A java -classpath AB.jar B 
+8
source share

Assuming 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

+4
source share

All Articles