Skip to content

Instantly share code, notes, and snippets.

@tschaub
Created June 27, 2011 21:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tschaub/1049963 to your computer and use it in GitHub Desktop.
Save tschaub/1049963 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
import java.util.List;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.commonjs.module.Require;
import org.mozilla.javascript.tools.shell.Global;
public class RhinoExample {
public static void main() {
Global global = new Global();
Context cx = Context.enter();
try {
global.initStandardObjects(cx, true);
cx.setLanguageVersion(170); // enable 1.7 language features
List<String> modulePaths = Arrays.asList("path/to/main", "path/to/my_modules");
Require require = global.installRequire(cx, modulePaths, false);
require.requireMain(cx, "main");
} finally {
Context.exit();
}
}
public static void add() {
Global global = new Global();
Context cx = Context.enter();
try {
global.initStandardObjects(cx, true);
cx.setLanguageVersion(170); // enable 1.7 language features
List<String> modulePaths = Arrays.asList("path/to/my_modules");
Require require = global.installRequire(cx, modulePaths, false);
Scriptable exports = (Scriptable) require.call(cx, global, global, new String[] {"math"});
Function add = (Function) exports.get("add", exports);
Object result = add.call(cx, global, global, new Object[] {2, 4});
// do something with result ...
} finally {
Context.exit();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment