简体   繁体   English

从另一个Java应用程序启动Java类

[英]Launch Java class from another Java application

Is there a way to launch a java class (and pass it a classpath and libary path) from within a Java application with out using Runtime.exec ? 有没有办法在Java应用程序中使用Runtime.exec启动java类(并将其传递给类路径和libary路径)?

I have seen: Launch a java application from another java application 我看到: 从另一个java应用程序启动一个java应用程序

but need to be able to pass a CLASSPATH and libary path. 但需要能够传递CLASSPATH和libary路径。

I am trying to make a launcher that a user downloads, it downloads the required files and then launches them. 我正在尝试制作用户下载的启动器,它会下载所需的文件然后启动它们。

Thank You 谢谢

https://stackoverflow.com/a/5575619/20394 should explain how to add to the library path and still use the same JVM. https://stackoverflow.com/a/5575619/20394应该解释如何添加到库路径并仍然使用相同的JVM。

To add to the classpath, create your own URLClassLoader and use that to find the class you want to load, then call its start method reflectively. 要添加到类路径,请创建自己的URLClassLoader并使用它来查找要加载的类,然后反射调用其start方法。

URLClassLoader classLoader = new URLClassLoader(
    urlsToDirectoriesAndJars, getClass().getClassLoader());
Class<?> myMainClass = classLoader.findClass("pkg.path.for.MainClass");
Method main = myMainClass.getMethod("main", String[].class);
main.invoke(null, new Object[] { new String[] { "args", "for", "main" } });

You'll need to handle some exceptions that are thrown by the reflective API but that's the gist of it. 您需要处理反射API抛出的一些异常,但这是它的要点。

If that class calls System.exit , then see How to prevent calls to System.exit() from terminating the JVM? 如果该类调用System.exit ,那么请参阅如何阻止对System.exit()的调用终止JVM?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM