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

5
  • 2
    Have you explored Java Web Start? Commented Jan 27, 2012 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 Commented Jan 27, 2012 at 11:09
  • @adarshr Exactly what I was thinking, but slightly different link. It includes links to a variety of helpful pages on JWS, including Oracle's own page on it. Commented Jan 27, 2012 at 11:11
  • "I want.." Why? What advantage does that provide to the end user? Commented Jan 27, 2012 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. Commented Jan 27, 2012 at 11:23

1 Answer 1

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?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.