Call Java methods from shell scripts

How to execute Java method from internal shell scripts?

+7
source share
3 answers

You can only call the main method. Create your main method so that it calls the method you want.

When I say the call method to main , you are not explicitly calling it. This is the only entry point to the java program when it is called.

If your class looks like this:

 package com.foo; public class Test { public static void main(String[] args) { System.out.println("Hello World!"); } } 

You can use the following command line to call main from a directory where you can find com/foo/Test.class (if you are in the classes directory in the structure shown below):

 java com.foo.Test 

If you want to do this from another (see the directory below), then you will need to set the class path.

 java -cp /path/to/classes com.foo.Test 

For clarity, suppose the directory structure is lower.

 -path -to -classes -com -foo >Test.class 
+10
source

You cannot execute an arbitrary method directly from a shell script, you will need to somehow open this method from the outside.

The easiest way is to write a main method that directly calls the code you want to test.

Alternatively, you can use a Java application that takes parameters to act as a kind of launcher. In its roughest form, you can imagine an application that takes a class name and a method name as arguments, then instantiates the class and calls the method through reflection. In a similar vein, but a little more elegant, we use an application that invokes operations opened through JMX to run certain methods on the server if necessary.

Ultimately, although bash (or the equivalent) does not understand the JVM bytecode. You will need to start the Java process to start the method, which will include the execution of some main method, which, in turn, calls what you need.

+2
source

You can use a shell script and call your java program as follows:

 `#!/bin/bash JAVA_HOME=/usr/lib/jvm/jdk1.6.0_02 CLASSPATH=/home/freddy/myapp/lib/whatever.jar: . $JAVA_HOME/bin/java -cp $CLASSPATH MyJavaClass exit 0` 
0
source

All Articles