How to run a jar file from another jar

北城以北 提交于 2019-12-01 13:38:43

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...

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!