0
# Mozilla Rhino JavaScript Engine
1
2
Mozilla Rhino is a Java implementation of JavaScript that enables embedding JavaScript execution capabilities within Java applications. It provides full ECMAScript compliance with extensive Java-JavaScript interoperability, making it ideal for server-side scripting, application extensibility, and Java-based JavaScript evaluation.
3
4
## Package Information
5
6
- **Package Name**: org.mozilla:rhino
7
- **Package Type**: maven
8
- **Language**: Java
9
- **Installation**: `<dependency><groupId>org.mozilla</groupId><artifactId>rhino</artifactId><version>1.8.0</version></dependency>`
10
11
## Core Imports
12
13
```java
14
import org.mozilla.javascript.Context;
15
import org.mozilla.javascript.ContextFactory;
16
import org.mozilla.javascript.Scriptable;
17
import org.mozilla.javascript.ScriptableObject;
18
import org.mozilla.javascript.Function;
19
import org.mozilla.javascript.Script;
20
```
21
22
## Basic Usage
23
24
```java
25
import org.mozilla.javascript.*;
26
27
public class RhinoExample {
28
public static void main(String[] args) {
29
// Create and enter a Context
30
Context cx = Context.enter();
31
try {
32
// Initialize the standard objects (Object, Function, etc.)
33
Scriptable scope = cx.initStandardObjects();
34
35
// Evaluate a JavaScript expression
36
Object result = cx.evaluateString(scope, "1 + 2", "<cmd>", 1, null);
37
System.out.println("Result: " + Context.toString(result)); // "3"
38
39
// Execute a more complex script
40
String script = """
41
function factorial(n) {
42
return n <= 1 ? 1 : n * factorial(n - 1);
43
}
44
factorial(5);
45
""";
46
Object factorial = cx.evaluateString(scope, script, "factorial.js", 1, null);
47
System.out.println("Factorial: " + Context.toString(factorial)); // "120"
48
49
} finally {
50
// Exit from the Context
51
Context.exit();
52
}
53
}
54
}
55
```
56
57
## Architecture
58
59
Mozilla Rhino is built around several key components:
60
61
- **Context Management**: `Context` and `ContextFactory` classes manage JavaScript execution environments with thread safety and configuration
62
- **Scriptable Interface**: Core abstraction for all JavaScript objects, providing property access and prototype chain management
63
- **Native Objects**: Complete implementations of JavaScript built-in objects (Array, Object, Function, Promise, etc.)
64
- **Java Integration**: Seamless bidirectional communication between Java and JavaScript with automatic type conversion
65
- **Compilation System**: Advanced parsing, compilation, and optimization capabilities with AST access
66
- **Security Framework**: Fine-grained access control for sandboxed execution environments
67
68
## Capabilities
69
70
### Context and Script Execution
71
72
Core JavaScript execution engine with context management, script compilation, and evaluation capabilities. Supports both interpreted and compiled execution modes.
73
74
```java { .api }
75
// Context management
76
public static Context enter();
77
public static void exit();
78
public static Context getCurrentContext();
79
public void close(); // Implements Closeable
80
81
// Script compilation and execution
82
public Object evaluateString(Scriptable scope, String source, String sourceName, int lineno, Object securityDomain);
83
public Object evaluateReader(Scriptable scope, Reader in, String sourceName, int lineno, Object securityDomain) throws IOException;
84
public Script compileString(String source, String sourceName, int lineno, Object securityDomain);
85
public Script compileReader(Reader in, String sourceName, int lineno, Object securityDomain) throws IOException;
86
public Function compileFunction(Scriptable scope, String source, String sourceName, int lineno, Object securityDomain);
87
public Object exec(Context cx, Scriptable scope); // Script interface
88
89
// Scope initialization
90
public ScriptableObject initStandardObjects();
91
public Scriptable initStandardObjects(ScriptableObject scope);
92
public ScriptableObject initStandardObjects(ScriptableObject scope, boolean sealed);
93
public ScriptableObject initSafeStandardObjects();
94
95
// Object creation
96
public Scriptable newObject(Scriptable scope);
97
public Scriptable newObject(Scriptable scope, String constructorName);
98
public Scriptable newObject(Scriptable scope, String constructorName, Object[] args);
99
public Scriptable newArray(Scriptable scope, int length);
100
public Scriptable newArray(Scriptable scope, Object[] elements);
101
102
// Decompilation
103
public String decompileScript(Script script, int indent);
104
public String decompileFunction(Function fun, int indent);
105
public String decompileFunctionBody(Function fun, int indent);
106
```
107
108
[Script Execution](./script-execution.md)
109
110
### JavaScript Objects and Natives
111
112
Complete JavaScript object system with all ECMAScript built-in objects, including ES6+ features like Promises, Symbols, Maps, and Sets.
113
114
```java { .api }
115
// Scriptable interface - core JavaScript object contract
116
public interface Scriptable {
117
Object get(String name, Scriptable start);
118
void put(String name, Scriptable start, Object value);
119
boolean has(String name, Scriptable start);
120
void delete(String name);
121
Scriptable getPrototype();
122
void setPrototype(Scriptable prototype);
123
String getClassName();
124
Object[] getIds();
125
}
126
127
// Native object creation (moved to Context section above)
128
// See Context API above for object creation methods
129
```
130
131
[JavaScript Objects](./javascript-objects.md)
132
133
### Java-JavaScript Integration
134
135
Seamless interoperability between Java and JavaScript with automatic type conversion, Java class access, and adapter objects.
136
137
```java { .api }
138
// Type conversion utilities
139
public static Object javaToJS(Object value, Scriptable scope);
140
public static Object javaToJS(Object value, Scriptable scope, Context cx);
141
public static Object jsToJava(Object value, Class<?> desiredType);
142
public static boolean toBoolean(Object value);
143
public static double toNumber(Object value);
144
public static String toString(Object value);
145
public static Scriptable toObject(Object value, Scriptable scope);
146
147
// Java object wrapping
148
public class WrapFactory {
149
public Object wrap(Context cx, Scriptable scope, Object obj, Class<?> staticType);
150
public Scriptable wrapAsJavaObject(Context cx, Scriptable scope, Object javaObject, Class<?> staticType);
151
}
152
```
153
154
[Java Integration](./java-integration.md)
155
156
### Security and Debugging
157
158
Comprehensive security framework with access control, sandboxing, and debugging support for production environments.
159
160
```java { .api }
161
// Security control
162
public interface ClassShutter {
163
boolean visibleToScripts(String fullClassName);
164
}
165
166
public class SecurityController {
167
public static SecurityController global();
168
public static void initGlobal(SecurityController controller);
169
}
170
171
// Debugging support
172
public interface Debugger {
173
void handleCompilationDone(Context cx, DebuggableScript fnOrScript, String source);
174
DebugFrame getFrame(Context cx, DebuggableScript fnOrScript);
175
}
176
```
177
178
[Security and Debugging](./security-debugging.md)
179
180
### Command Line Tools and Shell
181
182
Interactive JavaScript shell and command-line tools for script execution, compilation, and debugging.
183
184
```java { .api }
185
// Interactive shell main class
186
public class org.mozilla.javascript.tools.shell.Main {
187
/**
188
* Main entry point for Rhino shell
189
* @param args Command line arguments
190
*/
191
public static void main(String[] args);
192
193
/**
194
* Execute JavaScript code in shell context
195
* @param cx JavaScript context
196
* @param args Arguments to process
197
*/
198
public static void exec(String[] args);
199
}
200
201
// Enhanced global object with I/O capabilities
202
public class org.mozilla.javascript.tools.shell.Global extends ImporterTopLevel {
203
/**
204
* Initialize global object with standard functions plus I/O extensions
205
* @param cx Context for initialization
206
*/
207
public static Global initQuitAction(Context cx, Global global, boolean printAndQuit);
208
209
// Built-in shell functions available in global scope
210
public static void print(Context cx, Scriptable thisObj, Object[] args, Function funObj);
211
public static void quit(Context cx, Scriptable thisObj, Object[] args, Function funObj);
212
public static Object readFile(String path, String characterCoding) throws IOException;
213
public static Object readUrl(String url, String characterCoding) throws IOException;
214
public static String readline() throws IOException;
215
public static void write(String string);
216
public static void writeFile(String filename, String text, String characterCoding) throws IOException;
217
}
218
219
// Enhanced error reporting for command-line tools
220
public class org.mozilla.javascript.tools.ToolErrorReporter implements ErrorReporter {
221
/**
222
* Create error reporter for command-line tools
223
* @param reportWarnings Whether to report warnings
224
*/
225
public ToolErrorReporter(boolean reportWarnings);
226
227
/**
228
* Create error reporter with custom output stream
229
* @param reportWarnings Whether to report warnings
230
* @param out Output stream for errors
231
*/
232
public ToolErrorReporter(boolean reportWarnings, PrintStream out);
233
}
234
```
235
236
**Maven Dependency for Tools:**
237
```xml
238
<dependency>
239
<groupId>org.mozilla</groupId>
240
<artifactId>rhino-tools</artifactId>
241
<version>1.8.0</version>
242
</dependency>
243
```
244
245
**Usage Examples:**
246
247
```java
248
// Using shell Global object programmatically
249
Context cx = Context.enter();
250
try {
251
Global global = new Global();
252
global.init(cx);
253
254
// Global object includes print, quit, readFile, etc.
255
Object result = cx.evaluateString(global,
256
"print('Hello from Rhino!'); readFile('script.js');",
257
"shell", 1, null);
258
} finally {
259
Context.exit();
260
}
261
262
// Custom error reporting
263
ToolErrorReporter errorReporter = new ToolErrorReporter(true, System.err);
264
cx.setErrorReporter(errorReporter);
265
```
266
267
## Version and Language Support
268
269
```java { .api }
270
// Language version constants
271
public static final int VERSION_UNKNOWN = -1;
272
public static final int VERSION_DEFAULT = 0;
273
public static final int VERSION_1_0 = 100;
274
public static final int VERSION_1_1 = 110;
275
public static final int VERSION_1_2 = 120;
276
public static final int VERSION_1_3 = 130;
277
public static final int VERSION_1_4 = 140;
278
public static final int VERSION_1_5 = 150;
279
public static final int VERSION_1_6 = 160;
280
public static final int VERSION_1_7 = 170;
281
public static final int VERSION_1_8 = 180;
282
public static final int VERSION_ES6 = 200; // Default
283
public static final int VERSION_ECMASCRIPT = 250; // Latest features
284
285
// Version configuration
286
public int getLanguageVersion();
287
public void setLanguageVersion(int version);
288
public static boolean isValidLanguageVersion(int version);
289
public static void checkLanguageVersion(int version);
290
```
291
292
## Feature Configuration
293
294
```java { .api }
295
// Feature flags for controlling JavaScript behavior
296
public static final int FEATURE_NON_ECMA_GET_YEAR = 1;
297
public static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME = 2;
298
public static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER = 3;
299
public static final int FEATURE_TO_STRING_AS_SOURCE = 4;
300
public static final int FEATURE_PARENT_PROTO_PROPERTIES = 5;
301
public static final int FEATURE_E4X = 6; // E4X XML support
302
public static final int FEATURE_DYNAMIC_SCOPE = 7;
303
public static final int FEATURE_STRICT_VARS = 8;
304
public static final int FEATURE_STRICT_EVAL = 9;
305
public static final int FEATURE_LOCATION_INFORMATION_IN_ERROR = 10;
306
public static final int FEATURE_STRICT_MODE = 11;
307
public static final int FEATURE_WARNING_AS_ERROR = 12;
308
public static final int FEATURE_ENHANCED_JAVA_ACCESS = 13;
309
public static final int FEATURE_V8_EXTENSIONS = 14;
310
public static final int FEATURE_OLD_UNDEF_NULL_THIS = 15;
311
public static final int FEATURE_ENUMERATE_IDS_FIRST = 16;
312
public static final int FEATURE_THREAD_SAFE_OBJECTS = 17;
313
public static final int FEATURE_INTEGER_WITHOUT_DECIMAL_PLACE = 18;
314
public static final int FEATURE_LITTLE_ENDIAN = 19;
315
public static final int FEATURE_ENABLE_XML_SECURE_PARSING = 20;
316
public static final int FEATURE_ENABLE_JAVA_MAP_ACCESS = 21;
317
public static final int FEATURE_INTL_402 = 22; // Internationalization API
318
319
// Feature testing and configuration
320
public boolean hasFeature(int featureIndex);
321
```
322
323
## Core Interfaces
324
325
### Script and Function Interfaces
326
327
Essential interfaces for compiled scripts and callable functions that form the foundation of Rhino's execution model.
328
329
```java { .api }
330
// Script interface - all compiled scripts implement this
331
public interface Script {
332
/**
333
* Execute the script relative to a scope
334
* @param cx the Context associated with the current thread
335
* @param scope the scope to execute relative to
336
* @return the result of executing the script
337
*/
338
Object exec(Context cx, Scriptable scope);
339
}
340
341
// Function interface - all JavaScript functions implement this
342
public interface Function extends Scriptable, Callable, Constructable {
343
/**
344
* Call the function
345
* @param cx the current Context for this thread
346
* @param scope the scope to execute the function relative to
347
* @param thisObj the JavaScript 'this' object
348
* @param args the array of arguments
349
* @return the result of the call
350
*/
351
Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args);
352
353
/**
354
* Call the function as a constructor
355
* @param cx the current Context for this thread
356
* @param scope an enclosing scope of the caller
357
* @param args the array of arguments
358
* @return the allocated object
359
*/
360
Scriptable construct(Context cx, Scriptable scope, Object[] args);
361
}
362
363
// Callable interface - generic callable object
364
public interface Callable {
365
/**
366
* Perform the call
367
* @param cx the current Context for this thread
368
* @param scope the scope to use to resolve properties
369
* @param thisObj the JavaScript 'this' object
370
* @param args the array of arguments
371
* @return the result of the call
372
*/
373
Object call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args);
374
}
375
376
// Constructable interface - objects that can be constructed
377
public interface Constructable {
378
/**
379
* Call the function as a constructor
380
* @param cx the current Context for this thread
381
* @param scope an enclosing scope of the caller
382
* @param args the array of arguments
383
* @return the allocated object
384
*/
385
Scriptable construct(Context cx, Scriptable scope, Object[] args);
386
}
387
```
388
389
## Error Handling
390
391
```java { .api }
392
// Exception hierarchy
393
public abstract class RhinoException extends RuntimeException {
394
public String sourceName();
395
public int lineNumber();
396
public String lineSource();
397
public int columnNumber();
398
}
399
400
public class EvaluatorException extends RhinoException; // Compilation errors
401
public class EcmaError extends RhinoException; // JavaScript errors
402
public class JavaScriptException extends RhinoException; // Thrown values
403
public class WrappedException extends EvaluatorException; // Java exceptions
404
public class ContinuationPending extends RuntimeException; // Continuation support
405
406
// Error reporting
407
public interface ErrorReporter {
408
void warning(String message, String sourceName, int line, String lineSource, int lineOffset);
409
void error(String message, String sourceName, int line, String lineSource, int lineOffset);
410
EvaluatorException runtimeError(String message, String sourceName, int line, String lineSource, int lineOffset);
411
}
412
```
413
414
## Thread Safety and Context Factory
415
416
```java { .api }
417
// Context factory for thread-safe Context creation
418
public class ContextFactory {
419
public static ContextFactory getGlobal();
420
public Context enterContext();
421
public <T> T call(ContextAction<T> action);
422
}
423
424
// Context action for safe Context usage
425
public interface ContextAction<T> {
426
T run(Context cx);
427
}
428
```