Reputation:
I want to run a runnable jar archive from within my running Java application. I need to be able to control the running classes from within my application (i.e. Stop, start them etc).
Basically I need to do the eqvilient of "java -jar X.jar".
I cannot use Runtime.getRuntime().exec("...") as the jar files will be encoded and they need to be decoded first.
Upvotes: 5
Views: 718
Reputation: 122990
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"}});
}
}
Upvotes: 9
Reputation: 114817
An 'Executable Jar' is a simple jar file where the manifest has a special property which defines 'the' main class.
So you simply can put your executable jar on the classpath, identify the 'main' class and call the static main method of this class.
Upvotes: 4