Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>To use the load function in js embedded from Java, you must first expose it in on the scripting context. There's probably a way to do it from Java, but you can do it using js as well. </p> <p>Disclaimer: this solution uses source code taken from an Apache-licensed project I have been working on. You can see the original source file <a href="https://svn.apache.org/repos/asf/commons/sandbox/gsoc/2010/scxml-js/trunk/build-common.xml" rel="nofollow">here</a>.</p> <p>This js file sets up your global variables, and lives in a file named setupglobals.js:</p> <pre><code>var shell = org.mozilla.javascript.tools.shell.Main; var args = ["-e","var a='STRING';"]; shell.exec(args); var shellGlobal = shell.global; //grab functions from shell global and place in current global load=shellGlobal.load; print=shellGlobal.print; defineClass=shellGlobal.defineClass; deserialize=shellGlobal.deserialize; doctest=shellGlobal.doctest; gc=shellGlobal.gc; help=shellGlobal.help; loadClass=shellGlobal.loadClass; quit=shellGlobal.quit; readFile=shellGlobal.readFile; readUrl=shellGlobal.readUrl; runCommand=shellGlobal.runCommand; seal=shellGlobal.seal; serialize=shellGlobal.serialize; spawn=shellGlobal.spawn; sync=shellGlobal.sync; toint32=shellGlobal.toint32; version=shellGlobal.version; environment=shellGlobal.environment; </code></pre> <p>Here is your original Java host file, now augmented to evaluate setupglobals.js before any other scripts:</p> <pre><code>import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import org.mozilla.javascript.*; public class RhinoRunner { public static void main(String args[]) throws IOException { BufferedReader script = new BufferedReader(new FileReader("setupglobals.js")); BufferedReader script2 = new BufferedReader(new FileReader("example.js")); Context context = Context.enter(); try { ScriptableObject scope = context.initStandardObjects(); context.evaluateReader(scope, script, "script", 1, null); context.evaluateReader(scope, script2, "script2", 1, null); Function fct = (Function)scope.get("abc", scope); Object result = fct.call(context, scope, scope, new Object[] {2, 3}); System.out.println(Context.jsToJava(result, int.class)); } finally { Context.exit(); } } } </code></pre> <p>Here is your example.js, now augmented to use the global load function to load the file hello.js:</p> <pre><code>function abc(x,y) { return x+y } load("hello.js") </code></pre> <p>And finally, here is hello.js:</p> <pre><code>print("hello world!") </code></pre> <p>When executed, RhinoRunner prints the following:</p> <pre><code>hello world! 5 </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload