MCPcopy Create free account
hub / github.com/mozilla/rhino / main

Method main

examples/src/main/java/RunScript3.java:70–106  ·  view source on GitHub ↗

Main method that evaluates JavaScript code and then accesses JavaScript variables and functions from Java. This method demonstrates advanced JavaScript-Java integration using the Mozilla Rhino engine. After executing JavaScript code, it inspects the JavaScript scope to access variables and call

(String args[])

Source from the content-addressed store, hash-verified

68 * demonstration of Java-JavaScript variable and function access.
69 */
70 public static void main(String args[]) {
71 Context cx = Context.enter();
72 try {
73 TopLevel scope = cx.initStandardObjects();
74
75 // Collect the arguments into a single string.
76 String s = "";
77 for (int i = 0; i < args.length; i++) {
78 s += args[i];
79 }
80
81 // Now evaluate the string we've collected. We'll ignore the result.
82 cx.evaluateString(scope, s, "<cmd>", 1, null);
83
84 // Print the value of variable "x"
85 Object x = scope.get("x", scope);
86 if (x == Scriptable.NOT_FOUND) {
87 System.out.println("x is not defined.");
88 } else {
89 System.out.println("x = " + Context.toString(x));
90 }
91
92 // Call function "f('my arg')" and print its result.
93 Object fObj = scope.get("f", scope);
94 if (!(fObj instanceof Function)) {
95 System.out.println("f is undefined or not a function.");
96 } else {
97 Object functionArgs[] = {"my arg"};
98 Function f = (Function) fObj;
99 Object result = f.call(cx, scope, scope.getGlobalThis(), functionArgs);
100 String report = "f('my args') = " + Context.toString(result);
101 System.out.println(report);
102 }
103 } finally {
104 Context.exit();
105 }
106 }
107
108 /** Private constructor to prevent instantiation of this utility class. */
109 private RunScript3() {

Callers

nothing calls this directly

Calls 9

enterMethod · 0.95
initStandardObjectsMethod · 0.95
evaluateStringMethod · 0.95
getMethod · 0.95
toStringMethod · 0.95
callMethod · 0.95
getGlobalThisMethod · 0.95
exitMethod · 0.95
printlnMethod · 0.65

Tested by

no test coverage detected