Reputation: 38694
I want to load and execute external jar file using URLClassLoader.
What is the easiest way to get "Main-Class" from it?
Upvotes: 12
Views: 12589
Reputation: 100
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.
Upvotes: 7
Reputation: 65486
From here - Listing the main attributes of a jarfile
import java.util.*;
import java.util.jar.*;
import java.io.*;
public class MainJarAtr{
public static void main(String[] args){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.print("Enter jar file name: ");
String filename = in.readLine();
if(!filename.endsWith(".jar")){
System.out.println("File not in jar format.");
System.exit(0);
}
File file = new File(filename);
if (file.exists()){
// Open the JAR file
JarFile jarfile = new JarFile(filename);
// Get the manifest
Manifest manifest = jarfile.getManifest();
// Get the main attributes in the manifest
Attributes attrs = (Attributes)manifest.getMainAttributes();
// Enumerate each attribute
for (Iterator it=attrs.keySet().iterator(); it.hasNext(); ) {
// Get attribute name
Attributes.Name attrName = (Attributes.Name)it.next();
System.out.print(attrName + ": ");
// Get attribute value
String attrValue = attrs.getValue(attrName);
System.out.print(attrValue);
System.out.println();
}
}
else{
System.out.print("File not found.");
System.exit(0);
}
}
catch (IOException e) {}
}
}
Upvotes: 5
Reputation: 11638
This will only be possible if the jar is self-executing; in which case the main class will be specified in the manifest file with the key Main-Class:
Some reference information is provided here: http://docs.oracle.com/javase/tutorial/deployment/jar/appman.html
You will need to download the jarfile then use java.util.JarFile
to access it; some java code for this might be:
JarFile jf = new JarFile(new File("downloaded-file.jar"));
if(jf.getManifest().getEntries().containsKey("Main-Class")) {
String mainClassName = jf.getManifest().getEntries().get("Main-Class");
}
Upvotes: 5