Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get name of main class of a jar file from Java?

I want to load and execute external jar file using URLClassLoader.

What is the easiest way to get "Main-Class" from it?

like image 596
Vi. Avatar asked Dec 16 '11 12:12

Vi.


People also ask

How do I find the main class of a JAR file?

Technically a jar file can contain more than one main class. When java executes a jar file, it looks in the META-INF/MANIFEST. MF file inside the jar to find the entrypoint. There is no direct command to get this information, but you can unpack the jar (it's just a zip file) and look into the manifest yourself.

How do I extract a class from a JAR file?

You can open the jar file with winrar, this will show all the class files within, from there, you can drag them all into JD-GUI and decompile them all.

What is main class name in Java?

The main class can have any name, although typically it will just be called "Main".


1 Answers

I know this is an old question but, at least with the JDK 1.7, the previously proposed solutions did not seem to work. For this reason I am posting mine:

JarFile j = new JarFile(new File("jarfile.jar"));
String mainClassName = j.getManifest().getMainAttributes().getValue("Main-Class");

The reason why the other solutions did not work for me was because j.getManifest().getEntries() turns out to not contain the Main-Class attribute, that was instead contained in the list returned by the getMainAttributes() method.

like image 148
ma1069 Avatar answered Oct 03 '22 21:10

ma1069