Here's an example of pulling the name of the Main-Class
from the jar file using a JarFile
then loading the class from the jar using a URLClassLoader
and then invoking static void main
using reflection:
package test;
import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
public class JarRunner {
public static void main(String[] args) throws Exception{
File jar = new File(args[0]);
URLClassLoader classLoader = new URLClassLoader(
new URL[]{jar.toURL()}
);
JarFile jarFile = new JarFile(jar);
Attributes attribs = jarFile.getManifest().getMainAttributes();
String mainClass = attribs.getValue("Main-Class");
Class<?> clazz = classLoader.loadClass(mainClass);
Method main = clazz.getMethod("main", String[].class);
main.invoke(null, new Object[]{new String[]{"arg0", "arg1"}});
}
}