0

I need develop a "launcher" for a java application. This launcher need be able to:

  1. check if main application is up-to-date;
  2. if not, download a update;
  3. run this application and self terminate.

Something like this:

public final class Launcher {
  public static void main(String[] args) throws Exception {
    String jarName = args[0];

    if (jarHasUpdate(jarName)
      refreshJar(jarName);

    executeJar(jarName);
  }
}

What better way of develop the step 3?

I'm trying 2 distinct ways:

1- Run another instance of Java

With the code:

Runtime.getRuntime().exec("java -jar mainApp.jar");

Problem: the launcher still running until mainApp have finished.

2- Using ClassLoader to load .jar at runtime

Like this:

public final class Launcher {
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public static void main(String[] args) throws Exception {
        if (args.length < 2) {
            System.out.println("Invalid number of arguments.");
            System.exit(1);
    }

    Refresh.refreshFile(args[0]);

    // args[0] .jar name
    // args[1] class with main function
    File file = new File(args[0]);

    try (URLClassLoader cl = new URLClassLoader(new URL[] { file.toURI().toURL() });) {
        Class cls = cl.loadClass(args[1]);
        Method method = cls.getDeclaredMethod("main", new Class[] { String[].class });
        Object params = new String[] {};
        method.invoke(cls, params);
        }
    }
}

Problem: if "mainApp.jar" has dependencies, this isn't loaded.

4

0 回答 0