ALM ALM - 4 months ago 50
Java Question

Can not find or load class with Java ProcessBuilder using -cp and jar location

I am trying to use

ProcessBuilder
to start a JUnit test within my
Java
Application.

I am able to run the same command from the command line without issue. Do I need to use the absolute path for the jar when running from ProcessBuilder or can I use the relative path?

Running on the command line

java -cp .;lib/junit-4.12.jar org.junit.runner.JUnitCore com.test.Test1


Running inside my application

The junit library is in the lib folder

application/lib/junit-4.12.jar

ProcessBuilder builder = new ProcessBuilder(new String[] {"java", "-cp", ".;lib/junit-4.12.jar", "com.test.Test1"});

Process process = builder.start();
process.waitFor();

debug("process ended");
debug("process.exitValue() = " + process.exitValue());


Output:

process ended
process.exitValue() = 1
Error: Could not find or load main class org.junit.runner.JUnitCore

Answer

You can find what the classpath is when you run your application by using System.getProperty("java.class.path"); Then, modify "cp" in your ProcessBuilder() statement accordingly.