3

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

Community
  • 1
  • 1
WookooUK
  • 156
  • 9
  • 2
    Have you explored [Java Web Start](http://www.oracle.com/technetwork/java/javase/tech/index-jsp-136112.html)? – adarshr Jan 27 '12 at 11:07
  • I want the user to download a file to anywhere on their machine, and the files to be downloaded to their home folder: windows %appdata%\folderName mac/linux ~/folderName – WookooUK Jan 27 '12 at 11:09
  • @adarshr Exactly what I was thinking, but slightly [different link](http://stackoverflow.com/tags/java-web-start/info). It includes links to a variety of helpful pages on JWS, including Oracle's own page on it. – Andrew Thompson Jan 27 '12 at 11:11
  • *"I want.."* Why? What advantage does that provide to the end user? – Andrew Thompson Jan 27 '12 at 11:13
  • Its a game that I am making a launcher, the game does not support mac and linux and I have created the launcher to pull download the game, download all the extra libs and files needed to make it work on linux/mac and play the game. exactly how the minecraft launcher works. it grabs the natives for lwjgl and hides everything in the user-home and the user just has to worry about the one tiny exe that they can keep anywhere on their system. – WookooUK Jan 27 '12 at 11:23

1 Answers1

4

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?

Community
  • 1
  • 1
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245