Running jar archive in a running Java application

I want to run a runnable jar archive from my startup Java application. I need to be able to manage running classes from my application (i.e. stop, start them, etc.).

Basically I need to make an eqvilient from java -jar X.jar.

I can not use Runtime.getRuntime (). exec ("..."), because the jar files will be encoded and must be decoded first.

+5
source share
2 answers

Here is an example of pulling a name Main-Classfrom a jar file using JarFile, then loading a class from jar using URLClassLoaderand then calling static void mainusing 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"}});
    }
}
+9
source

An "Executable Jar" - jar, , " ".

, , "main" .

+4

All Articles