tags:

views:

326

answers:

2

Hi all,

I am new to java programming. 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.

+4  A: 

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.

Andreas_D
Might want to use a custom ClassLoader or URLClassLoader.newInstance to load the classes dynamically.
Tom Hawtin - tackline
+7  A: 

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"}});
    }
}
Aaron Maenpaa
+1 for the brilliant demonstration for Classloader, JarFile and reflection. But everybody who is New To Java should note, that the targets main mathod is invoked with the arguments 'arg0' and 'arg1'. A real world implementation has to replace these Strings with real arguments.
Andreas_D
A minor fix is required if the "main class" also happens to be on your classpath: "URLClassLoader classLoader = new URLClassLoader(new URL[]{jar.toURL(), null});". This prevents delegation to the current classloader, which can cause dependent classes in the JAR file to fail to load.
plinehan