My task is to create two simple programs with output, put them both into one jar-archive and execute programs one by one.
I can do it with one program using this commands:
creating jar – jar cfe <name-of-the-archieve>.jar <main-class-name> *.class *.java
,
executing program – java -jar <name-of-the-archieve>.jar
, but the thing is that I don’t know how to do it properly with more than one program.
The code from both programs is identical:
System.out.println("<some message>")
Advertisement
Answer
You just need to give the class name when you run the JVM:
P1.java
public class P1 { public static void main(String... args) { System.out.println("P1"); } }
P2.java
public class P2 { public static void main(String... args) { System.out.println("P2"); } }
Then we can run the following commands:
javac P1.java P2.java jar -cf sample.jar P1.class P2.class java -cp sample.jar P1 P1 java -cp sample.jar P2 P2
We don’t use the manifest to specify the main class, and so don’t have an executable jar file. We explicitly tell the JVM which class to run.
You can still create an executable jar file to provide a ‘default’ class to execute when you run with the -jar
option. Even with a Main-Class:
entry in your MANIFEST.MF you can explicitly run the main
from a different class with java -cp sample.jar <class name>
.