How to run a jar file from another jar

前端 未结 2 369
梦毁少年i
梦毁少年i 2021-01-15 09:43

I have a jar file that has been turned into a .exe using L4J, and another jar file in appdata. The reason for having two files is that I need an updating mechanism.

相关标签:
2条回答
  • 2021-01-15 10:20

    You could use a URLClassLoader to load the second Jar at runtime.

    Depending on your needs, you may need a bridging interface (one that exists in both Jars) that you would call from your 'exe' to get the second Jar running...or you could simply use the second Jar's main method ;)

    The other choice you have is to run another JVM.

    UPDATE

    In order to physical seperate the two elements of your application. You have a Jar wrapped in a EXE (aka launcher) and another Jar which is your application (aka application) (I assume).

    So. Your launcher should have absolutely no idea about your application (little to no compile time dependencies).

    Some how, we need to dynamically load the application from the launcher. To do that, we need a few things.

    We need to be able to load the application into the launchers class loader context (so we can see it) and we some we to be able to load the application.

    Dynamic ClassLoading

    This can be achieved simply through the use of URLClassLoader

    URLClassLoader loader = new URLClassLoader(new URL[]{new File("path/to/your/jar/Application.jar").toURI().toURL()});
    

    Application Loading

    This can be achieved in one of two ways. You could simply use the URLClassLoader to find a launch the applications main class...

    // This is essentially the same as saying 
    // the.package.name.to.you.main.class.Main.main(new String[]{});
    Class<?> mainClass = loader.loadClass("the.package.name.to.you.main.class.Main");
    Method mainMethod = mainClass.getMethod("main", String[].class);
    mainMethod.invoke(null, new String[]{});
    

    Now, if your application Jar doesn't have a main method, you can use the above example to launch just about any class you want...

    0 讨论(0)
  • 2021-01-15 10:26

    you need to add a jar, by at to classpath, for eg: "c:\mypath\myjar.jar" than you will update that myjar.jar

    0 讨论(0)
提交回复
热议问题