Search code examples
javaprocessjarclasspathprocessbuilder

Creating java process to execute class within current jar


So hopefully the title covers the jist, I am aware there are multiple posts around this kind of thing, the issue I am specifically having is how to set the classpath for the jar i am currently running which contains the class.

i.e I have packaged my jar with all dependencies exploded within, using the Maven assembly plugin. So I am simply trying to create a sub process to execute one of the dependency classes existing in my jar, from within my jar. If thats possible?

Thanks to the post below here is the solution:

URL baseUrl = getClass().getProtectionDomain().getCodeSource().getLocation();
                String myPath = (new File(baseUrl.toURI())).getCanonicalPath();

ProcessBuilder pb = new ProcessBuilder("javaw", "-cp", myPath,
 "jp.vmi.selenium.selenese.Main", config.getSuite().getAbsolutePath());

pb.redirectErrorStream(true);

try
{
    Process proc = pb.start();

    InputStream is = proc.getInputStream();
    BufferedInputStream bis = new BufferedInputStream(is);

    int c;

    while ((c = bis.read()) != -1)
    {
        System.out.write(c);
    }

    int exit = proc.waitFor();

Any pointers in the right direction would be greatly appreciated.

Thanks,


Solution

  • OK, if you absolutely must, you may try this snippet to find your "current" JAR:

    try
        {
            URL baseUrl = JavaApplication2.class.getProtectionDomain().getCodeSource().getLocation();
            String myPath = (new File(baseUrl.toURI())).getCanonicalPath();
            System.out.println("Path is " + myPath);
        }
        catch (IOException ex)
        {
           // Deal with exception 
        }
        catch (URISyntaxException ex)
        {
           // Deal with exception 
        }
    

    Instead of "JavaApplication2" use any class in your application/JAR. (or just getClass(), should also work in non-statical context)