简体   繁体   中英

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 ?

I have seen: Launch a java application from another java application

but need to be able to pass a CLASSPATH and libary path.

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.

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

If that class calls System.exit , then see How to prevent calls to System.exit() from terminating the JVM?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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