Starting a Java process with the same executable as the current one

I have Java code that starts a new Java process, effectively using the default JRE system (in my case, JDK 8). Instead, I need it to start with a version that starts the original process (e.g. JDK 9).

How can i do this? (The solution should work on both Java 8 and 9.)

More details

Currently, the code relies on the default JRE system by simply issuing the java ... command. An alternative would be to use something similar to System.getProperty("java.home") + "/bin/java" (but not platform dependent), but both have the same problem (for me): they start the Java process with a version of the JVM known to the system.

UPDATE This is completely wrong, System.getProperty("java.home") really does what I want and returns the current JVM home directory. (Stupid me, I thought I tried this.)

One way to start with the same Java version is to request the current process for its executable and reuse, but I did not find an API for it.

+5
source share
2 answers

If you still cannot use the new Java 9 API, you are here:

 static String getJavaRuntime() throws IOException { String os = System.getProperty("os.name"); String java = System.getProperty("java.home") + File.separator + "bin" + File.separator + (os != null && os.toLowerCase(Locale.ENGLISH).startsWith("windows") ? "java.exe" : "java"); if (!new File(java).isFile()) { throw new IOException("Unable to find suitable java runtime at "+java); } return java; } 

For more information, you can see how we do this in the JOSM reboot action , which has the following requirements:

  • work on Java 8+, Linux, Windows and macOS
  • work with java directly with a jar file or class files (for example, from the IDE)
  • working with Java Web Start and macOS packaged applications
  • work with paths containing white space characters

The code runs as follows:

  • finds a java runtime using the java.home system property
  • checks if the system property sun.java.command (not for IBM JVM), and then extracts the main program class and program parameters from it.
  • restores the command line either by adding the arguments -cp or -jar , depending on what we found in the previous step
  • runs the command using Runtime.getRuntime().exec

There are also many things regarding JNLP (WebStart) and macOS applications. I assume you are not interested in this, but I can explain it if you want.

+3
source

Solution only for Java 9. Using

 ProcessHandle.current().info().command().map(Paths::get).orElseThrow(); 

you get the handle to the current java executable: <JAVA_HOME>/bin/java[.exe]

Now use this (absolute) path with the new process API to your liking.

+3
source

Source: https://habr.com/ru/post/1274248/


All Articles