How to run a class from Jar which is not the Main-Class in its Manifest file
You can execute any class which has a public static void main
method from a JAR file, even if the jar file has a Main-Class
defined.
Execute Main-Class:
java -jar MyJar.jar // will execute the Main-Class
Execute another class with a public static void main
method:
java -cp MyJar.jar com.mycomp.myproj.AnotherClassWithMainMethod
Note: the first uses -jar
, the second uses -cp
.
This answer is for Spring-boot users:
If your JAR was from a Spring-boot
project and created using the command mvn package spring-boot:repackage
, the above "-cp" method won't work. You will get:
Error: Could not find or load main class your.alternative.class.path
even if you can see the class in the JAR by jar tvf yours.jar
.
In this case, run your alternative class by the following command:
java -cp yours.jar -Dloader.main=your.alternative.class.path org.springframework.boot.loader.PropertiesLauncher
As I understood, the Spring-boot's org.springframework.boot.loader.PropertiesLauncher
class serves as a dispatching entrance class, and the -Dloader.main
parameter tells it what to run.
Reference: https://github.com/spring-projects/spring-boot/issues/20404
You can create your jar without Main-Class in its Manifest file. Then :
java -cp MyJar.jar com.mycomp.myproj.dir2.MainClass2 /home/myhome/datasource.properties /home/myhome/input.txt