Top Rounds
| We are Hiring! |

Sahi Scripting - Calling Java ·

Sahi scripts run on the Rhino javascript engine. This allows Sahi to call any Java code in the classpath of Sahi.

Calling Java code only requires prepending the full package name with “Packages.”

Below is a simple example to print on the console.

function printThroughJava(s){
    Packages.java.lang.System.out.println("Through Java: " + s);
}
printThroughJava("Hi there");
// Should print "Through Java: Hi there" on the console.

Another thing to note is that Javascript does not have types, so variable types are declared with just var.

For example:

function printThroughJava(s){
    var sysout = Packages.java.lang.System.out; 
    // sysout would have been of type java.io.PrintStream in java. 
    // but here declared with only var
    sysout.println("Through Java: " + s);
}

This is how _readFile is implemented in Sahi:

// Part of lib.js
// Note: ""+ is used to convert Java string to Javascript string
Sahi.prototype._readFile = function (filePath) {
    return "" + Packages.net.sf.sahi.util.Utils.readFileAsString(filePath);
};

Have a look at Rhino’s documentation for a detailed discussion on Scripting Java through Rhino



---


Top Rounds