Vik
Vik

Reputation: 9289

invoking command line java from java code accepting arguments

I am able to invoke a java class using below command line:

java -jar <my jar name>.jar -option1 <option> "<a string value>"

However, I want to invoke it from a another Java program. The name of the main class is XYZ

I have imported the jar as a dependency in my project.

Upvotes: 1

Views: 49

Answers (1)

ernest_k
ernest_k

Reputation: 45309

That heavily depends on whether you want to launch it as a separate process or simply execute within the same one.

To kick it off in the same process, you could just call the main method:

String[] arguments = new String[]{"-option1", "<option>", "<a string value>"};
MyOtherMainClass.main(arguments);

To start it as a different process:

ProcessBuilder pb = new ProcessBuilder("java", "-jar", "<my jar name>.jar", "-option1", "<option>", "<a string value>");
Process process = pb.start();
int errCode = process.waitFor();

The second example was inspired by http://examples.javacodegeeks.com/core-java/lang/processbuilder/java-lang-processbuilder-example/

Upvotes: 1

Related Questions