Executing JAR file within another java application

删除回忆录丶 提交于 2019-12-06 04:33:44

Why can't you just set your classpath so that it includes the second jar, and then you can simply use it as a library ? You can even invoke the MainClass.main() method manually, if you really want that to be executed, but from within the same VM and without spawning a separate process.

EDIT: If you don't know the name of the jar file when your application is launched, but you'll only figure that out at runtime, in order to invoke it, create a URLClassLoader provided with the path to your jar file and then:

URLClassLoader urlClassLoader = new URLClassLoader(
        new File("/path/to/your/jar/file.jar").toURI().toURL() );

ClassLoader cl = Thread.currentThread().getContextClassLoader();
// switch to your custom CL
Thread.currentThread().setContextClassLoader(urlClassLoader);
// do your stuff with the other jar
// ....................
// now switch back to the original CL
Thread.currentThread().setContextClassLoader(cl);

Or simply grab a reference to a class in that other jar and make use of reflection:

Class<?> c = urlClassLoader.loadClass("org.ogher.packag.ClassFromExternalJar");
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!