⇤ ← Revision 1 as of 2013-08-16 17:00:24
Size: 1694
Comment:
|
Size: 1726
Comment:
|
Deletions are marked like this. | Additions are marked like this. |
Line 1: | Line 1: |
## page was renamed from rhino |
rhino
Rhino is an open-source implementation of JavaScript written entirely in Java.
It is typically embedded into Java applications to provide scripting to end users.
It is embedded in J2SE 6 as the default Java scripting engine.
https://developer.mozilla.org/en-US/docs/Rhino
Invoke JavaScript from Java example
1 import javax.script.Invocable;
2 import javax.script.ScriptEngine;
3 import javax.script.ScriptEngineManager;
4 import javax.script.ScriptException;
5 import java.io.FileNotFoundException;
6 import java.io.FileReader;
7
8 public class JSTest {
9
10 /**
11 * @param args
12 */
13 public static void main(String[] args) {
14 ScriptEngineManager sem = new ScriptEngineManager();
15 ScriptEngine engine = sem.getEngineByName("ECMAScript");
16 FileReader fr = null;
17 String path = "/tmp/test.js";
18 try {
19 fr = new FileReader(path);
20 } catch (FileNotFoundException e) {
21 System.out.println(String.format("File %s not found", path));
22 }
23
24 if (fr != null) {
25 try {
26 engine.eval(fr);
27 if (engine instanceof Invocable) {
28 Invocable iv = (Invocable) engine;
29
30 try {
31 System.out.println(iv.invokeFunction("isOdd", new Integer(4)));
32 System.out.println(iv.invokeFunction("isOdd", new Integer(5)));
33 } catch (NoSuchMethodException ex) {
34 ex.printStackTrace();
35 } catch (ScriptException ex) {
36 ex.printStackTrace();
37 }
38 }
39 } catch (ScriptException ex) {
40 ex.printStackTrace();
41 }
42 }
43 }
44
45 }