Class Context
- java.lang.Object
- 
- org.mozilla.javascript.Context
 
- 
- All Implemented Interfaces:
- java.io.Closeable,- java.lang.AutoCloseable
 
 public class Context extends java.lang.Object implements java.io.CloseableThis class represents the runtime context of an executing script.Before executing a script, an instance of Context must be created and associated with the thread that will be executing the script. The Context will be used to store information about the executing of the script such as the call stack. Contexts are associated with the current thread using the call(ContextAction)orenter()methods.Different forms of script execution are supported. Scripts may be evaluated from the source directly, or first compiled and then later executed. Interactive execution is also supported. Some aspects of script execution, such as type conversions and object creation, may be accessed directly through methods of Context. - See Also:
- Scriptable
 
- 
- 
Nested Class SummaryNested Classes Modifier and Type Class Description static interfaceContext.ClassShutterSetter
 - 
Field SummaryFields Modifier and Type Field Description static java.lang.Object[]emptyArgsConvenient value to use as zero-length array of objects.static java.lang.StringerrorReporterPropertystatic intFEATURE_DYNAMIC_SCOPEControl if dynamic scope should be used for name access.static intFEATURE_E4XControl if support for E4X(ECMAScript for XML) extension is available.static intFEATURE_ENABLE_JAVA_MAP_ACCESSConfigure whether the entries in a Java Map can be accessed by properties.static intFEATURE_ENABLE_XML_SECURE_PARSINGConfigure the XMLProcessor to parse XML with security features or not.static intFEATURE_ENHANCED_JAVA_ACCESSEnables enhanced access to Java.static intFEATURE_ENUMERATE_IDS_FIRSTIf set, then the order of property key enumeration will be first numeric keys in numeric order, followed by string keys in order of creation, and finally Symbol keys, as specified in ES6.static intFEATURE_INTEGER_WITHOUT_DECIMAL_PLACEIf set, then all integer numbers will be returned without decimal place.static intFEATURE_INTL_402Internationalization API implementation (see https://tc39.github.io/ecma402) can be activated using this feature.static intFEATURE_LITTLE_ENDIANTypedArray buffer uses little/big endian depending on the platform.static intFEATURE_LOCATION_INFORMATION_IN_ERRORWhen the feature is on Rhino will add a "fileName" and "lineNumber" properties to Error objects automatically.static intFEATURE_MEMBER_EXPR_AS_FUNCTION_NAMEControl if member expression as function name extension is available.static intFEATURE_NON_ECMA_GET_YEARControls behaviour ofDate.prototype.getYear().static intFEATURE_OLD_UNDEF_NULL_THISDefines how an undefined "this" parameter is handled in certain calls.static intFEATURE_PARENT_PROTO_PROPERTIESControl if properties__proto__and__parent__are treated specially.static intFEATURE_PARENT_PROTO_PROPRTIESDeprecated.In previous releases, this name was given to FEATURE_PARENT_PROTO_PROPERTIES.static intFEATURE_RESERVED_KEYWORD_AS_IDENTIFIERControl if reserved keywords are treated as identifiers.static intFEATURE_STRICT_EVALControl if strict eval mode is enabled.static intFEATURE_STRICT_MODEControls whether JS 1.5 'strict mode' is enabled.static intFEATURE_STRICT_VARSControl if strict variable mode is enabled.static intFEATURE_THREAD_SAFE_OBJECTSIf set, then all objects will have a thread-safe property map.static intFEATURE_TO_STRING_AS_SOURCEControl iftoString()should returns the same result astoSource()when applied to objects and arrays.static intFEATURE_V8_EXTENSIONSEnables access to JavaScript features from ECMAscript 6 that are present in JavaScript engines that do not yet support version 6, such as V8.static intFEATURE_WARNING_AS_ERRORControls whether a warning should be treated as an error.booleangenerateObserverCountstatic java.lang.StringlanguageVersionPropertystatic intVERSION_1_0JavaScript 1.0static intVERSION_1_1JavaScript 1.1static intVERSION_1_2JavaScript 1.2static intVERSION_1_3JavaScript 1.3static intVERSION_1_4JavaScript 1.4static intVERSION_1_5JavaScript 1.5static intVERSION_1_6JavaScript 1.6static intVERSION_1_7JavaScript 1.7static intVERSION_1_8JavaScript 1.8static intVERSION_DEFAULTThe default version.static intVERSION_ES6ECMAScript 6.static intVERSION_UNKNOWNThe unknown version.
 - 
Constructor SummaryConstructors Modifier Constructor Description Context()Deprecated.this constructor is deprecated because it creates a dependency on a static singleton context factory.protectedContext(ContextFactory factory)Creates a new context.
 - 
Method SummaryAll Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description voidaddActivationName(java.lang.String name)Add a name to the list of names forcing the creation of real activation objects for functions.static voidaddContextListener(ContextListener listener)Deprecated.voidaddPropertyChangeListener(java.beans.PropertyChangeListener l)Register an object to receive notifications when a bound property has changedstatic <T> Tcall(ContextAction<T> action)Deprecated.useContextFactory.call(ContextAction)instead as this method relies on usage of a static singleton "global" ContextFactory.static java.lang.Objectcall(ContextFactory factory, Callable callable, Scriptable scope, Scriptable thisObj, java.lang.Object[] args)CallCallable.call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args)using the Context instance associated with the current thread.java.lang.ObjectcallFunctionWithContinuations(Callable function, Scriptable scope, java.lang.Object[] args)Call function that may pause execution by capturing a continuation.ContinuationPendingcaptureContinuation()Capture a continuation from the current execution.static voidcheckLanguageVersion(int version)static voidcheckOptimizationLevel(int optimizationLevel)voidclose()FunctioncompileFunction(Scriptable scope, java.lang.String source, java.lang.String sourceName, int lineno, java.lang.Object securityDomain)Compile a JavaScript function.protected java.lang.ObjectcompileImpl(Scriptable scope, java.lang.String sourceString, java.lang.String sourceName, int lineno, java.lang.Object securityDomain, boolean returnFunction, Evaluator compiler, ErrorReporter compilationErrorReporter)ScriptcompileReader(java.io.Reader in, java.lang.String sourceName, int lineno, java.lang.Object securityDomain)Compiles the source in the given reader.ScriptcompileReader(Scriptable scope, java.io.Reader in, java.lang.String sourceName, int lineno, java.lang.Object securityDomain)Deprecated.ScriptcompileString(java.lang.String source, java.lang.String sourceName, int lineno, java.lang.Object securityDomain)Compiles the source in the given string.GeneratedClassLoadercreateClassLoader(java.lang.ClassLoader parent)Create class loader for generated classes.java.lang.StringdecompileFunction(Function fun, int indent)Decompile a JavaScript Function.java.lang.StringdecompileFunctionBody(Function fun, int indent)Decompile the body of a JavaScript Function.java.lang.StringdecompileScript(Script script, int indent)Decompile the script.voidenqueueMicrotask(java.lang.Runnable task)Add a task that will be executed at the end of the current operation.static Contextenter()Same as callingContextFactory.enterContext()on the global ContextFactory instance.static Contextenter(Context cx)Deprecated.useContextFactory.enterContext(Context)instead as this method relies on usage of a static singleton "global" ContextFactory.java.lang.ObjectevaluateReader(Scriptable scope, java.io.Reader in, java.lang.String sourceName, int lineno, java.lang.Object securityDomain)Evaluate a reader as JavaScript source.java.lang.ObjectevaluateString(Scriptable scope, java.lang.String source, java.lang.String sourceName, int lineno, java.lang.Object securityDomain)Evaluate a JavaScript source string.java.lang.ObjectexecuteScriptWithContinuations(Script script, Scriptable scope)Execute script that may pause execution by capturing a continuation.static voidexit()Exit a block of code requiring a Context.java.lang.ClassLoadergetApplicationClassLoader()Context.ClassShutterSettergetClassShutterSetter()static ContextgetCurrentContext()Get the current Context.static DebuggableScriptgetDebuggableView(Script script)Return DebuggableScript instance if any associated with the script.DebuggergetDebugger()Return the current debugger.java.lang.ObjectgetDebuggerContextData()Return the debugger context data associated with current context.XMLLib.FactorygetE4xImplementationFactory()Returns an object which specifies an E4X implementation to use within thisContext.java.lang.Object[]getElements(Scriptable object)Get the elements of a JavaScript array.ErrorReportergetErrorReporter()Get the current error reporter.ContextFactorygetFactory()ReturnContextFactoryinstance used to create this Context.java.lang.StringgetImplementationVersion()Get the implementation version.intgetInstructionObserverThreshold()Get threshold of executed instructions counter that triggers call toobserveInstructionCount().java.util.function.UnaryOperator<java.lang.Object>getJavaToJSONConverter()Returns the javaToJSONConverter for this Context.intgetLanguageVersion()Get the current language version.java.util.LocalegetLocale()Get the current locale.intgetMaximumInterpreterStackDepth()Returns the maximum stack depth (in terms of number of call frames) allowed in a single invocation of interpreter.intgetOptimizationLevel()Get the current optimization level.java.lang.ObjectgetThreadLocal(java.lang.Object key)Get a value corresponding to a key.java.util.TimeZonegetTimeZone()Get the current timezone.static java.lang.ObjectgetUndefinedValue()Get the singleton object that represents the JavaScript Undefined value.UnhandledRejectionTrackergetUnhandledPromiseTracker()Return the object used to track unhandled promise rejections.WrapFactorygetWrapFactory()Return the current WrapFactory, or null if none is defined.booleanhasFeature(int featureIndex)Controls certain aspects of script semantics.ScriptableObjectinitSafeStandardObjects()Initialize the standard objects, leaving out those that offer access directly to Java classes.ScriptableinitSafeStandardObjects(ScriptableObject scope)Initialize the standard objects, leaving out those that offer access directly to Java classes.ScriptableObjectinitSafeStandardObjects(ScriptableObject scope, boolean sealed)Initialize the standard objects, leaving out those that offer access directly to Java classes.ScriptableObjectinitStandardObjects()Initialize the standard objects.ScriptableinitStandardObjects(ScriptableObject scope)Initialize the standard objects.ScriptableObjectinitStandardObjects(ScriptableObject scope, boolean sealed)Initialize the standard objects.booleanisActivationNeeded(java.lang.String name)Check whether the name is in the list of names of objects forcing the creation of activation objects.static booleanisCurrentContextStrict()booleanisGeneratingDebug()Tell whether debug information is being generated.booleanisGeneratingDebugChanged()booleanisGeneratingSource()Tell whether source information is being generated.booleanisSealed()Checks if this is a sealed Context.booleanisStrictMode()static booleanisValidLanguageVersion(int version)static booleanisValidOptimizationLevel(int optimizationLevel)static java.lang.ObjectjavaToJS(java.lang.Object value, Scriptable scope)Convenient method to convert java value to its closest representation in JavaScript.static java.lang.ObjectjavaToJS(java.lang.Object value, Scriptable scope, Context cx)Convenient method to convert java value to its closest representation in JavaScript.static java.lang.ObjectjsToJava(java.lang.Object value, java.lang.Class<?> desiredType)Convert a JavaScript value into the desired type.ScriptablenewArray(Scriptable scope, int length)Create an array with a specified initial length.ScriptablenewArray(Scriptable scope, java.lang.Object[] elements)Create an array with a set of initial elements.ScriptablenewObject(Scriptable scope)Create a new JavaScript object.ScriptablenewObject(Scriptable scope, java.lang.String constructorName)Create a new JavaScript object by executing the named constructor.ScriptablenewObject(Scriptable scope, java.lang.String constructorName, java.lang.Object[] args)Creates a new JavaScript object by executing the named constructor.protected voidobserveInstructionCount(int instructionCount)Allow application to monitor counter of executed script instructions in Context subclasses.voidprocessMicrotasks()Run all the microtasks for the current context to completion.voidputThreadLocal(java.lang.Object key, java.lang.Object value)Put a value that can later be retrieved using a given key.voidremoveActivationName(java.lang.String name)Remove a name from the list of names forcing the creation of real activation objects for functions.static voidremoveContextListener(ContextListener listener)Deprecated.voidremovePropertyChangeListener(java.beans.PropertyChangeListener l)Remove an object from the list of objects registered to receive notification of changes to a bounded propertyvoidremoveThreadLocal(java.lang.Object key)Remove values from thread-local storage.static voidreportError(java.lang.String message)Report an error using the error reporter for the current thread.static voidreportError(java.lang.String message, java.lang.String sourceName, int lineno, java.lang.String lineSource, int lineOffset)Report an error using the error reporter for the current thread.static EvaluatorExceptionreportRuntimeError(java.lang.String message)Report a runtime error using the error reporter for the current thread.static EvaluatorExceptionreportRuntimeError(java.lang.String message, java.lang.String sourceName, int lineno, java.lang.String lineSource, int lineOffset)Report a runtime error using the error reporter for the current thread.static voidreportWarning(java.lang.String message)Report a warning using the error reporter for the current thread.static voidreportWarning(java.lang.String message, java.lang.String sourceName, int lineno, java.lang.String lineSource, int lineOffset)Report a warning using the error reporter for the current thread.static voidreportWarning(java.lang.String message, java.lang.Throwable t)java.lang.ObjectresumeContinuation(java.lang.Object continuation, Scriptable scope, java.lang.Object functionResult)Restarts execution of the JavaScript suspended at the call tocaptureContinuation().voidseal(java.lang.Object sealKey)voidsetApplicationClassLoader(java.lang.ClassLoader loader)static voidsetCachingEnabled(boolean cachingEnabled)Deprecated.voidsetClassShutter(ClassShutter shutter)Set the LiveConnect access filter for this context.voidsetDebugger(Debugger debugger, java.lang.Object contextData)Set the associated debugger.ErrorReportersetErrorReporter(ErrorReporter reporter)Change the current error reporter.voidsetGenerateObserverCount(boolean generateObserverCount)Turn on or off generation of code with callbacks to track the count of executed instructions.voidsetGeneratingDebug(boolean generatingDebug)Specify whether or not debug information should be generated.voidsetGeneratingSource(boolean generatingSource)Specify whether or not source information should be generated.voidsetInstructionObserverThreshold(int threshold)Set threshold of executed instructions counter that triggers call toobserveInstructionCount().voidsetJavaToJSONConverter(java.util.function.UnaryOperator<java.lang.Object> javaToJSONConverter)Sets the javaToJSONConverter for this Context.voidsetLanguageVersion(int version)Set the language version.java.util.LocalesetLocale(java.util.Locale loc)Set the current locale.voidsetMaximumInterpreterStackDepth(int max)Sets the maximum stack depth (in terms of number of call frames) allowed in a single invocation of interpreter.voidsetOptimizationLevel(int optimizationLevel)Set the current optimization level.voidsetSecurityController(SecurityController controller)Set the security controller for this context.java.util.TimeZonesetTimeZone(java.util.TimeZone tz)Set the current timezone.voidsetTrackUnhandledPromiseRejections(boolean track)Control whether to track unhandled promise rejections.voidsetWrapFactory(WrapFactory wrapFactory)Set a WrapFactory for this Context.booleanstringIsCompilableUnit(java.lang.String source)Check whether a string is ready to be compiled.static java.lang.RuntimeExceptionthrowAsScriptRuntimeEx(java.lang.Throwable e)Rethrow the exception wrapping it as the script runtime exception.static booleantoBoolean(java.lang.Object value)Convert the value to a JavaScript boolean value.static doubletoNumber(java.lang.Object value)Convert the value to a JavaScript Number value.static ScriptabletoObject(java.lang.Object value, Scriptable scope)Convert the value to an JavaScript object value.static ScriptabletoObject(java.lang.Object value, Scriptable scope, java.lang.Class<?> staticType)Deprecated.static java.lang.StringtoString(java.lang.Object value)Convert the value to a JavaScript String value.static java.lang.ObjecttoType(java.lang.Object value, java.lang.Class<?> desiredType)Deprecated.voidunseal(java.lang.Object sealKey)Unseal previously sealed Context object.
 
- 
- 
- 
Field Detail- 
VERSION_UNKNOWNpublic static final int VERSION_UNKNOWN The unknown version.Be aware, this version will not support many of the newer language features and will not change in the future. Please use one of the other constants like VERSION_ES6 to get support for recent language features. - See Also:
- Constant Field Values
 
 - 
VERSION_DEFAULTpublic static final int VERSION_DEFAULT The default version.- See Also:
- Constant Field Values
 
 - 
VERSION_1_0public static final int VERSION_1_0 JavaScript 1.0- See Also:
- Constant Field Values
 
 - 
VERSION_1_1public static final int VERSION_1_1 JavaScript 1.1- See Also:
- Constant Field Values
 
 - 
VERSION_1_2public static final int VERSION_1_2 JavaScript 1.2- See Also:
- Constant Field Values
 
 - 
VERSION_1_3public static final int VERSION_1_3 JavaScript 1.3- See Also:
- Constant Field Values
 
 - 
VERSION_1_4public static final int VERSION_1_4 JavaScript 1.4- See Also:
- Constant Field Values
 
 - 
VERSION_1_5public static final int VERSION_1_5 JavaScript 1.5- See Also:
- Constant Field Values
 
 - 
VERSION_1_6public static final int VERSION_1_6 JavaScript 1.6- See Also:
- Constant Field Values
 
 - 
VERSION_1_7public static final int VERSION_1_7 JavaScript 1.7- See Also:
- Constant Field Values
 
 - 
VERSION_1_8public static final int VERSION_1_8 JavaScript 1.8- See Also:
- Constant Field Values
 
 - 
VERSION_ES6public static final int VERSION_ES6 ECMAScript 6.- See Also:
- Constant Field Values
 
 - 
FEATURE_NON_ECMA_GET_YEARpublic static final int FEATURE_NON_ECMA_GET_YEAR Controls behaviour ofDate.prototype.getYear(). IfhasFeature(FEATURE_NON_ECMA_GET_YEAR)returns true, Date.prototype.getYear subtructs 1900 only if 1900 <= date < 2000. The default behavior ofhasFeature(int)is always to subtruct 1900 as rquired by ECMAScript B.2.4.- See Also:
- Constant Field Values
 
 - 
FEATURE_MEMBER_EXPR_AS_FUNCTION_NAMEpublic static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME Control if member expression as function name extension is available. IfhasFeature(FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME)returns true, allowfunction memberExpression(args) { body }to be syntax sugar formemberExpression = function(args) { body }, when memberExpression is not a simple identifier. See ECMAScript-262, section 11.2 for definition of memberExpression. By defaulthasFeature(int)returns false.- See Also:
- Constant Field Values
 
 - 
FEATURE_RESERVED_KEYWORD_AS_IDENTIFIERpublic static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER Control if reserved keywords are treated as identifiers. IfhasFeature(RESERVED_KEYWORD_AS_IDENTIFIER)returns true, treat future reserved keyword (see Ecma-262, section 7.5.3) as ordinary identifiers but warn about this usage.By default hasFeature(int)returns false.- See Also:
- Constant Field Values
 
 - 
FEATURE_TO_STRING_AS_SOURCEpublic static final int FEATURE_TO_STRING_AS_SOURCE Control iftoString()should returns the same result astoSource()when applied to objects and arrays. IfhasFeature(FEATURE_TO_STRING_AS_SOURCE)returns true, callingtoString()on JS objects gives the same result as callingtoSource(). That is it returns JS source with code to create an object with all enumeratable fields of the original object instead of printing[object result of.Scriptable.getClassName()]By default hasFeature(int)returns true only if the current JS version is set toVERSION_1_2.- See Also:
- Constant Field Values
 
 - 
FEATURE_PARENT_PROTO_PROPERTIESpublic static final int FEATURE_PARENT_PROTO_PROPERTIES Control if properties__proto__and__parent__are treated specially. IfhasFeature(FEATURE_PARENT_PROTO_PROPERTIES)returns true, treat__parent__and__proto__as special properties.The properties allow to query and set scope and prototype chains for the objects. The special meaning of the properties is available only when they are used as the right hand side of the dot operator. For example, while x.__proto__ = ychanges the prototype chain of the objectxto point toy,x["__proto__"] = ysimply assigns a new value to the property__proto__inxeven when the feature is on.By default hasFeature(int)returns true.- See Also:
- Constant Field Values
 
 - 
FEATURE_PARENT_PROTO_PROPRTIES@Deprecated public static final int FEATURE_PARENT_PROTO_PROPRTIES Deprecated.In previous releases, this name was given to FEATURE_PARENT_PROTO_PROPERTIES.- See Also:
- Constant Field Values
 
 - 
FEATURE_E4Xpublic static final int FEATURE_E4X Control if support for E4X(ECMAScript for XML) extension is available. If hasFeature(FEATURE_E4X) returns true, the XML syntax is available.By default hasFeature(int)returns true if the current JS version is set toVERSION_DEFAULTor is at leastVERSION_1_6.- Since:
- 1.6 Release 1
- See Also:
- Constant Field Values
 
 - 
FEATURE_DYNAMIC_SCOPEpublic static final int FEATURE_DYNAMIC_SCOPE Control if dynamic scope should be used for name access. If hasFeature(FEATURE_DYNAMIC_SCOPE) returns true, then the name lookup during name resolution will use the top scope of the script or function which is at the top of JS execution stack instead of the top scope of the script or function from the current stack frame if the top scope of the top stack frame contains the top scope of the current stack frame on its prototype chain.This is useful to define shared scope containing functions that can be called from scripts and functions using private scopes. By default hasFeature(int)returns false.- Since:
- 1.6 Release 1
- See Also:
- Constant Field Values
 
 - 
FEATURE_STRICT_VARSpublic static final int FEATURE_STRICT_VARS Control if strict variable mode is enabled. When the feature is on Rhino reports runtime errors if assignment to a global variable that does not exist is executed. When the feature is off such assignments create a new variable in the global scope as required by ECMA 262.By default hasFeature(int)returns false.- Since:
- 1.6 Release 1
- See Also:
- Constant Field Values
 
 - 
FEATURE_STRICT_EVALpublic static final int FEATURE_STRICT_EVAL Control if strict eval mode is enabled. When the feature is on Rhino reports runtime errors if non-string argument is passed to the eval function. When the feature is off eval simply return non-string argument as is without performing any evaluation as required by ECMA 262.By default hasFeature(int)returns false.- Since:
- 1.6 Release 1
- See Also:
- Constant Field Values
 
 - 
FEATURE_LOCATION_INFORMATION_IN_ERRORpublic static final int FEATURE_LOCATION_INFORMATION_IN_ERROR When the feature is on Rhino will add a "fileName" and "lineNumber" properties to Error objects automatically. When the feature is off, you have to explicitly pass them as the second and third argument to the Error constructor. Note that neither behavior is fully ECMA 262 compliant (as 262 doesn't specify a three-arg constructor), but keeping the feature off results in Error objects that don't have additional non-ECMA properties when constructed using the ECMA-defined single-arg constructor and is thus desirable if a stricter ECMA compliance is desired, specifically adherence to the point 15.11.5. of the standard.By default hasFeature(int)returns false.- Since:
- 1.6 Release 6
- See Also:
- Constant Field Values
 
 - 
FEATURE_STRICT_MODEpublic static final int FEATURE_STRICT_MODE Controls whether JS 1.5 'strict mode' is enabled. When the feature is on, Rhino reports more than a dozen different warnings. When the feature is off, these warnings are not generated. FEATURE_STRICT_MODE implies FEATURE_STRICT_VARS and FEATURE_STRICT_EVAL.By default hasFeature(int)returns false.- Since:
- 1.6 Release 6
- See Also:
- Constant Field Values
 
 - 
FEATURE_WARNING_AS_ERRORpublic static final int FEATURE_WARNING_AS_ERROR Controls whether a warning should be treated as an error.- Since:
- 1.6 Release 6
- See Also:
- Constant Field Values
 
 - 
FEATURE_ENHANCED_JAVA_ACCESSpublic static final int FEATURE_ENHANCED_JAVA_ACCESS Enables enhanced access to Java. Specifically, controls whether private and protected members can be accessed, and whether scripts can catch all Java exceptions.Note that this feature should only be enabled for trusted scripts. By default hasFeature(int)returns false.- Since:
- 1.7 Release 1
- See Also:
- Constant Field Values
 
 - 
FEATURE_V8_EXTENSIONSpublic static final int FEATURE_V8_EXTENSIONS Enables access to JavaScript features from ECMAscript 6 that are present in JavaScript engines that do not yet support version 6, such as V8. This includes support for typed arrays. Default is true.- Since:
- 1.7 Release 3
- See Also:
- Constant Field Values
 
 - 
FEATURE_OLD_UNDEF_NULL_THISpublic static final int FEATURE_OLD_UNDEF_NULL_THIS Defines how an undefined "this" parameter is handled in certain calls. Previously Rhino would convert an undefined "this" to null, whereas recent specs call for it to be treated differently. Default is to be set if language version <= 1.7.- Since:
- 1.7.7
- See Also:
- Constant Field Values
 
 - 
FEATURE_ENUMERATE_IDS_FIRSTpublic static final int FEATURE_ENUMERATE_IDS_FIRST If set, then the order of property key enumeration will be first numeric keys in numeric order, followed by string keys in order of creation, and finally Symbol keys, as specified in ES6. Default is true for language version >= "ES6" and false otherwise.- Since:
- 1.7.7.1
- See Also:
- Constant Field Values
 
 - 
FEATURE_THREAD_SAFE_OBJECTSpublic static final int FEATURE_THREAD_SAFE_OBJECTS If set, then all objects will have a thread-safe property map. (Note that this doesn't make everything else that they do thread-safe -- that depends on the specific implementation. If not set, users should not share Rhino objects between threads, unless the "sync" function is used to wrap them with an explicit synchronizer. The default is false, which means that by default, individual objects are not thread-safe.- Since:
- 1.7.8
- See Also:
- Constant Field Values
 
 - 
FEATURE_INTEGER_WITHOUT_DECIMAL_PLACEpublic static final int FEATURE_INTEGER_WITHOUT_DECIMAL_PLACE If set, then all integer numbers will be returned without decimal place. For instance assume there is a function like this:function foo() {return 5;}5 will be returned if feature is set, 5.0 otherwise.- See Also:
- Constant Field Values
 
 - 
FEATURE_LITTLE_ENDIANpublic static final int FEATURE_LITTLE_ENDIAN TypedArray buffer uses little/big endian depending on the platform. The default is big endian for Rhino.- Since:
- 1.7 Release 11
- See Also:
- Constant Field Values
 
 - 
FEATURE_ENABLE_XML_SECURE_PARSINGpublic static final int FEATURE_ENABLE_XML_SECURE_PARSING Configure the XMLProcessor to parse XML with security features or not. Security features include not fetching remote entity references and disabling XIncludes- Since:
- 1.7 Release 12
- See Also:
- Constant Field Values
 
 - 
FEATURE_ENABLE_JAVA_MAP_ACCESSpublic static final int FEATURE_ENABLE_JAVA_MAP_ACCESS Configure whether the entries in a Java Map can be accessed by properties.Not enabled: var map = new java.util.HashMap(); map.put('foo', 1); map.foo; // undefined Enabled: var map = new java.util.HashMap(); map.put('foo', 1); map.foo; // 1 WARNING: This feature is similar to the one in Nashorn, but incomplete. 1. A entry has priority over method. map.put("put", "abc"); map.put; // abc map.put("put", "efg"); // ERROR 2. The distinction between numeric keys and string keys is ambiguous. map.put('1', 123); map['1']; // Not found. This means `map[1]`. - Since:
- 1.7 Release 14
- See Also:
- Constant Field Values
 
 - 
FEATURE_INTL_402public static final int FEATURE_INTL_402 Internationalization API implementation (see https://tc39.github.io/ecma402) can be activated using this feature.- Since:
- 1.7 Release 15
- See Also:
- Constant Field Values
 
 - 
languageVersionPropertypublic static final java.lang.String languageVersionProperty - See Also:
- Constant Field Values
 
 - 
errorReporterPropertypublic static final java.lang.String errorReporterProperty - See Also:
- Constant Field Values
 
 - 
emptyArgspublic static final java.lang.Object[] emptyArgs Convenient value to use as zero-length array of objects.
 - 
generateObserverCountpublic boolean generateObserverCount 
 
- 
 - 
Constructor Detail- 
Context@Deprecated public Context() Deprecated.this constructor is deprecated because it creates a dependency on a static singleton context factory. UseContextFactory.enter()orContextFactory.call(ContextAction)instead. If you subclass this class, consider usingContext(ContextFactory)constructor instead in the subclasses' constructors.Creates a new Context. The context will be associated with theglobal context factory.Note that the Context must be associated with a thread before it can be used to execute a script. 
 - 
Contextprotected Context(ContextFactory factory) Creates a new context. Provided as a preferred super constructor for subclasses in place of the deprecated default public constructor.- Parameters:
- factory- the context factory associated with this context (most likely, the one that created the context). Can not be null. The context features are inherited from the factory, and the context will also otherwise use its factory's services.
- Throws:
- java.lang.IllegalArgumentException- if factory parameter is null.
 
 
- 
 - 
Method Detail- 
getCurrentContextpublic static Context getCurrentContext() Get the current Context.The current Context is per-thread; this method looks up the Context associated with the current thread. - Returns:
- the Context associated with the current thread, or null if no context is associated with the current thread.
- See Also:
- ContextFactory.enterContext(),- ContextFactory.call(ContextAction)
 
 - 
enterpublic static Context enter() Same as callingContextFactory.enterContext()on the global ContextFactory instance.- Returns:
- a Context associated with the current thread
- See Also:
- getCurrentContext(),- exit(),- call(ContextAction)
 
 - 
enter@Deprecated public static Context enter(Context cx) Deprecated.useContextFactory.enterContext(Context)instead as this method relies on usage of a static singleton "global" ContextFactory.Get a Context associated with the current thread, using the given Context if need be.The same as enter()except thatcxis associated with the current thread and returned if the current thread has no associated context andcxis not associated with any other thread.- Parameters:
- cx- a Context to associate with the thread if possible
- Returns:
- a Context associated with the current thread
- See Also:
- ContextFactory.enterContext(Context),- ContextFactory.call(ContextAction)
 
 - 
exitpublic static void exit() Exit a block of code requiring a Context.Calling exit()will remove the association between the current thread and a Context if the prior call toContextFactory.enterContext()on this thread newly associated a Context with this thread. Once the current thread no longer has an associated Context, it cannot be used to execute JavaScript until it is again associated with a Context.- See Also:
- ContextFactory.enterContext()
 
 - 
closepublic void close() - Specified by:
- closein interface- java.lang.AutoCloseable
- Specified by:
- closein interface- java.io.Closeable
 
 - 
call@Deprecated public static <T> T call(ContextAction<T> action) Deprecated.useContextFactory.call(ContextAction)instead as this method relies on usage of a static singleton "global" ContextFactory.CallContextAction.run(Context cx)using the Context instance associated with the current thread. If no Context is associated with the thread, thenContextFactory.getGlobal().makeContext()will be called to construct new Context instance. The instance will be temporary associated with the thread during call toContextAction.run(Context).- Returns:
- The result of ContextAction.run(Context).
 
 - 
callpublic static java.lang.Object call(ContextFactory factory, Callable callable, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) CallCallable.call(Context cx, Scriptable scope, Scriptable thisObj, Object[] args)using the Context instance associated with the current thread. If no Context is associated with the thread, thenContextFactory.makeContext()will be called to construct new Context instance. The instance will be temporary associated with the thread during call toContextAction.run(Context).It is allowed but not advisable to use null for factoryargument in which case the global static singleton ContextFactory instance will be used to create new context instances.- See Also:
- ContextFactory.call(ContextAction)
 
 - 
addContextListener@Deprecated public static void addContextListener(ContextListener listener) Deprecated.
 - 
removeContextListener@Deprecated public static void removeContextListener(ContextListener listener) Deprecated.
 - 
getFactorypublic final ContextFactory getFactory() ReturnContextFactoryinstance used to create this Context.
 - 
isSealedpublic final boolean isSealed() Checks if this is a sealed Context. A sealed Context instance does not allow to modify any of its properties and will throw an exception on any such attempt.- See Also:
- seal(Object sealKey)
 
 - 
sealpublic final void seal(java.lang.Object sealKey) Seal this Context object so any attempt to modify any of its properties including callingenter()andexit()methods will throw an exception.If sealKeyis not null, callingunseal(Object sealKey)with the same key unseals the object. IfsealKeyis null, unsealing is no longer possible.- See Also:
- isSealed(),- unseal(Object)
 
 - 
unsealpublic final void unseal(java.lang.Object sealKey) Unseal previously sealed Context object. ThesealKeyargument should not be null and should matchsealKeysuplied with the last call toseal(Object)or an exception will be thrown.- See Also:
- isSealed(),- seal(Object sealKey)
 
 - 
getLanguageVersionpublic final int getLanguageVersion() Get the current language version.The language version number affects JavaScript semantics as detailed in the overview documentation. - Returns:
- an integer that is one of VERSION_1_0, VERSION_1_1, etc.
 
 - 
setLanguageVersionpublic void setLanguageVersion(int version) Set the language version.Setting the language version will affect functions and scripts compiled subsequently. See the overview documentation for version-specific behavior. - Parameters:
- version- the version as specified by VERSION_1_0, VERSION_1_1, etc.
 
 - 
isValidLanguageVersionpublic static boolean isValidLanguageVersion(int version) 
 - 
checkLanguageVersionpublic static void checkLanguageVersion(int version) 
 - 
getImplementationVersionpublic final java.lang.String getImplementationVersion() Get the implementation version.The implementation version is of the form "name langVerwhere name is the name of the product, langVer is the language version, relNum is the release number, and date is the release date for that specific release in the form "yyyy mm dd".releaserelNum date"- Returns:
- a string that encodes the product, language version, release number, and date.
 
 - 
getErrorReporterpublic final ErrorReporter getErrorReporter() Get the current error reporter.- See Also:
- ErrorReporter
 
 - 
setErrorReporterpublic final ErrorReporter setErrorReporter(ErrorReporter reporter) Change the current error reporter.- Returns:
- the previous error reporter
- See Also:
- ErrorReporter
 
 - 
getLocalepublic final java.util.Locale getLocale() Get the current locale. Returns the default locale if none has been set.- See Also:
- Locale
 
 - 
setLocalepublic final java.util.Locale setLocale(java.util.Locale loc) Set the current locale.- Returns:
- the old value of the locale
- See Also:
- Locale
 
 - 
getTimeZonepublic final java.util.TimeZone getTimeZone() Get the current timezone. Returns the default timezone if none has been set.- Returns:
- the old value of the timezone
- See Also:
- TimeZone
 
 - 
setTimeZonepublic final java.util.TimeZone setTimeZone(java.util.TimeZone tz) Set the current timezone.- See Also:
- TimeZone
 
 - 
addPropertyChangeListenerpublic final void addPropertyChangeListener(java.beans.PropertyChangeListener l) Register an object to receive notifications when a bound property has changed- Parameters:
- l- the listener
- See Also:
- PropertyChangeEvent,- removePropertyChangeListener(java.beans.PropertyChangeListener)
 
 - 
removePropertyChangeListenerpublic final void removePropertyChangeListener(java.beans.PropertyChangeListener l) Remove an object from the list of objects registered to receive notification of changes to a bounded property- Parameters:
- l- the listener
- See Also:
- PropertyChangeEvent,- addPropertyChangeListener(java.beans.PropertyChangeListener)
 
 - 
reportWarningpublic static void reportWarning(java.lang.String message, java.lang.String sourceName, int lineno, java.lang.String lineSource, int lineOffset)Report a warning using the error reporter for the current thread.- Parameters:
- message- the warning message to report
- sourceName- a string describing the source, such as a filename
- lineno- the starting line number
- lineSource- the text of the line (may be null)
- lineOffset- the offset into lineSource where problem was detected
- See Also:
- ErrorReporter
 
 - 
reportWarningpublic static void reportWarning(java.lang.String message) Report a warning using the error reporter for the current thread.- Parameters:
- message- the warning message to report
- See Also:
- ErrorReporter
 
 - 
reportWarningpublic static void reportWarning(java.lang.String message, java.lang.Throwable t)
 - 
reportErrorpublic static void reportError(java.lang.String message, java.lang.String sourceName, int lineno, java.lang.String lineSource, int lineOffset)Report an error using the error reporter for the current thread.- Parameters:
- message- the error message to report
- sourceName- a string describing the source, such as a filename
- lineno- the starting line number
- lineSource- the text of the line (may be null)
- lineOffset- the offset into lineSource where problem was detected
- See Also:
- ErrorReporter
 
 - 
reportErrorpublic static void reportError(java.lang.String message) Report an error using the error reporter for the current thread.- Parameters:
- message- the error message to report
- See Also:
- ErrorReporter
 
 - 
reportRuntimeErrorpublic static EvaluatorException reportRuntimeError(java.lang.String message, java.lang.String sourceName, int lineno, java.lang.String lineSource, int lineOffset) Report a runtime error using the error reporter for the current thread.- Parameters:
- message- the error message to report
- sourceName- a string describing the source, such as a filename
- lineno- the starting line number
- lineSource- the text of the line (may be null)
- lineOffset- the offset into lineSource where problem was detected
- Returns:
- a runtime exception that will be thrown to terminate the execution of the script
- See Also:
- ErrorReporter
 
 - 
reportRuntimeErrorpublic static EvaluatorException reportRuntimeError(java.lang.String message) Report a runtime error using the error reporter for the current thread.- Parameters:
- message- the error message to report
- See Also:
- ErrorReporter
 
 - 
initStandardObjectspublic final ScriptableObject initStandardObjects() Initialize the standard objects.Creates instances of the standard objects and their constructors (Object, String, Number, Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. This method must be called to initialize a scope before scripts can be evaluated in that scope. This method does not affect the Context it is called upon. - Returns:
- the initialized scope
 
 - 
initSafeStandardObjectspublic final ScriptableObject initSafeStandardObjects() Initialize the standard objects, leaving out those that offer access directly to Java classes. This sets up "scope" to have access to all the standard JavaScript classes, but does not create global objects for any top-level Java packages. In addition, the "Packages," "JavaAdapter," and "JavaImporter" classes, and the "getClass" function, are not initialized.The result of this function is a scope that may be safely used in a "sandbox" environment where it is not desirable to give access to Java code from JavaScript. Creates instances of the standard objects and their constructors (Object, String, Number, Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. This method must be called to initialize a scope before scripts can be evaluated in that scope. This method does not affect the Context it is called upon. - Returns:
- the initialized scope
 
 - 
initStandardObjectspublic final Scriptable initStandardObjects(ScriptableObject scope) Initialize the standard objects.Creates instances of the standard objects and their constructors (Object, String, Number, Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. This method must be called to initialize a scope before scripts can be evaluated in that scope. This method does not affect the Context it is called upon. - Parameters:
- scope- the scope to initialize, or null, in which case a new object will be created to serve as the scope
- Returns:
- the initialized scope. The method returns the value of the scope argument if it is
     not null or newly allocated scope object which is an instance ScriptableObject.
 
 - 
initSafeStandardObjectspublic final Scriptable initSafeStandardObjects(ScriptableObject scope) Initialize the standard objects, leaving out those that offer access directly to Java classes. This sets up "scope" to have access to all the standard JavaScript classes, but does not create global objects for any top-level Java packages. In addition, the "Packages," "JavaAdapter," and "JavaImporter" classes, and the "getClass" function, are not initialized.The result of this function is a scope that may be safely used in a "sandbox" environment where it is not desirable to give access to Java code from JavaScript. Creates instances of the standard objects and their constructors (Object, String, Number, Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. This method must be called to initialize a scope before scripts can be evaluated in that scope. This method does not affect the Context it is called upon. - Parameters:
- scope- the scope to initialize, or null, in which case a new object will be created to serve as the scope
- Returns:
- the initialized scope. The method returns the value of the scope argument if it is
     not null or newly allocated scope object which is an instance ScriptableObject.
 
 - 
initStandardObjectspublic ScriptableObject initStandardObjects(ScriptableObject scope, boolean sealed) Initialize the standard objects.Creates instances of the standard objects and their constructors (Object, String, Number, Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. This method must be called to initialize a scope before scripts can be evaluated in that scope. This method does not affect the Context it is called upon. This form of the method also allows for creating "sealed" standard objects. An object that is sealed cannot have properties added, changed, or removed. This is useful to create a "superglobal" that can be shared among several top-level objects. Note that sealing is not allowed in the current ECMA/ISO language specification, but is likely for the next version. - Parameters:
- scope- the scope to initialize, or null, in which case a new object will be created to serve as the scope
- sealed- whether or not to create sealed standard objects that cannot be modified.
- Returns:
- the initialized scope. The method returns the value of the scope argument if it is not null or newly allocated scope object.
- Since:
- 1.4R3
 
 - 
initSafeStandardObjectspublic ScriptableObject initSafeStandardObjects(ScriptableObject scope, boolean sealed) Initialize the standard objects, leaving out those that offer access directly to Java classes. This sets up "scope" to have access to all the standard JavaScript classes, but does not create global objects for any top-level Java packages. In addition, the "Packages," "JavaAdapter," and "JavaImporter" classes, and the "getClass" function, are not initialized.The result of this function is a scope that may be safely used in a "sandbox" environment where it is not desirable to give access to Java code from JavaScript. Creates instances of the standard objects and their constructors (Object, String, Number, Date, etc.), setting up 'scope' to act as a global object as in ECMA 15.1. This method must be called to initialize a scope before scripts can be evaluated in that scope. This method does not affect the Context it is called upon. This form of the method also allows for creating "sealed" standard objects. An object that is sealed cannot have properties added, changed, or removed. This is useful to create a "superglobal" that can be shared among several top-level objects. Note that sealing is not allowed in the current ECMA/ISO language specification, but is likely for the next version. - Parameters:
- scope- the scope to initialize, or null, in which case a new object will be created to serve as the scope
- sealed- whether or not to create sealed standard objects that cannot be modified.
- Returns:
- the initialized scope. The method returns the value of the scope argument if it is not null or newly allocated scope object.
- Since:
- 1.7.6
 
 - 
getUndefinedValuepublic static java.lang.Object getUndefinedValue() Get the singleton object that represents the JavaScript Undefined value.
 - 
evaluateStringpublic final java.lang.Object evaluateString(Scriptable scope, java.lang.String source, java.lang.String sourceName, int lineno, java.lang.Object securityDomain) Evaluate a JavaScript source string.The provided source name and line number are used for error messages and for producing debug information. - Parameters:
- scope- the scope to execute in
- source- the JavaScript source
- sourceName- a string describing the source, such as a filename
- lineno- the starting line number
- securityDomain- an arbitrary object that specifies security information about the origin or owner of the script. For implementations that don't care about security, this value may be null.
- Returns:
- the result of evaluating the string
- See Also:
- SecurityController
 
 - 
evaluateReaderpublic final java.lang.Object evaluateReader(Scriptable scope, java.io.Reader in, java.lang.String sourceName, int lineno, java.lang.Object securityDomain) throws java.io.IOException Evaluate a reader as JavaScript source.All characters of the reader are consumed. - Parameters:
- scope- the scope to execute in
- in- the Reader to get JavaScript source from
- sourceName- a string describing the source, such as a filename
- lineno- the starting line number
- securityDomain- an arbitrary object that specifies security information about the origin or owner of the script. For implementations that don't care about security, this value may be null.
- Returns:
- the result of evaluating the source
- Throws:
- java.io.IOException- if an IOException was generated by the Reader
 
 - 
executeScriptWithContinuationspublic java.lang.Object executeScriptWithContinuations(Script script, Scriptable scope) throws ContinuationPending Execute script that may pause execution by capturing a continuation. Caller must be prepared to catch a ContinuationPending exception and resume execution by callingresumeContinuation(Object, Scriptable, Object).- Parameters:
- script- The script to execute. Script must have been compiled with interpreted mode (optimization level -1)
- scope- The scope to execute the script against
- Throws:
- ContinuationPending- if the script calls a function that results in a call to- captureContinuation()
- Since:
- 1.7 Release 2
 
 - 
callFunctionWithContinuationspublic java.lang.Object callFunctionWithContinuations(Callable function, Scriptable scope, java.lang.Object[] args) throws ContinuationPending Call function that may pause execution by capturing a continuation. Caller must be prepared to catch a ContinuationPending exception and resume execution by callingresumeContinuation(Object, Scriptable, Object).- Parameters:
- function- The function to call. The function must have been compiled with interpreted mode (optimization level -1)
- scope- The scope to execute the script against
- args- The arguments for the function
- Throws:
- ContinuationPending- if the script calls a function that results in a call to- captureContinuation()
- Since:
- 1.7 Release 2
 
 - 
captureContinuationpublic ContinuationPending captureContinuation() Capture a continuation from the current execution. The execution must have been started via a call toexecuteScriptWithContinuations(Script, Scriptable)orcallFunctionWithContinuations(Callable, Scriptable, Object[]). This implies that the code calling this method must have been called as a function from the JavaScript script. Also, there cannot be any non-JavaScript code between the JavaScript frames (e.g., a call to eval()). The ContinuationPending exception returned must be thrown.- Returns:
- A ContinuationPending exception that must be thrown
- Since:
- 1.7 Release 2
 
 - 
resumeContinuationpublic java.lang.Object resumeContinuation(java.lang.Object continuation, Scriptable scope, java.lang.Object functionResult) throws ContinuationPendingRestarts execution of the JavaScript suspended at the call tocaptureContinuation(). Execution of the code will resume with the functionResult as the result of the call that captured the continuation. Execution of the script will either conclude normally and the result returned, another continuation will be captured and thrown, or the script will terminate abnormally and throw an exception.- Parameters:
- continuation- The value returned by- ContinuationPending.getContinuation()
- functionResult- This value will appear to the code being resumed as the result of the function that captured the continuation
- Throws:
- ContinuationPending- if another continuation is captured before the code terminates
- Since:
- 1.7 Release 2
 
 - 
stringIsCompilableUnitpublic final boolean stringIsCompilableUnit(java.lang.String source) Check whether a string is ready to be compiled.stringIsCompilableUnit is intended to support interactive compilation of JavaScript. If compiling the string would result in an error that might be fixed by appending more source, this method returns false. In every other case, it returns true. Interactive shells may accumulate source lines, using this method after each new line is appended to check whether the statement being entered is complete. - Parameters:
- source- the source buffer to check
- Returns:
- whether the source is ready for compilation
- Since:
- 1.4 Release 2
 
 - 
compileReader@Deprecated public final Script compileReader(Scriptable scope, java.io.Reader in, java.lang.String sourceName, int lineno, java.lang.Object securityDomain) throws java.io.IOException Deprecated.- Throws:
- java.io.IOException
- See Also:
- compileReader(Reader in, String sourceName, int lineno, Object securityDomain)
 
 - 
compileReaderpublic final Script compileReader(java.io.Reader in, java.lang.String sourceName, int lineno, java.lang.Object securityDomain) throws java.io.IOException Compiles the source in the given reader.Returns a script that may later be executed. Will consume all the source in the reader. - Parameters:
- in- the input reader
- sourceName- a string describing the source, such as a filename
- lineno- the starting line number for reporting errors
- securityDomain- an arbitrary object that specifies security information about the origin or owner of the script. For implementations that don't care about security, this value may be null.
- Returns:
- a script that may later be executed
- Throws:
- java.io.IOException- if an IOException was generated by the Reader
- See Also:
- Script
 
 - 
compileStringpublic final Script compileString(java.lang.String source, java.lang.String sourceName, int lineno, java.lang.Object securityDomain) Compiles the source in the given string.Returns a script that may later be executed. - Parameters:
- source- the source string
- sourceName- a string describing the source, such as a filename
- lineno- the starting line number for reporting errors. Use 0 if the line number is unknown.
- securityDomain- an arbitrary object that specifies security information about the origin or owner of the script. For implementations that don't care about security, this value may be null.
- Returns:
- a script that may later be executed
- See Also:
- Script
 
 - 
compileFunctionpublic final Function compileFunction(Scriptable scope, java.lang.String source, java.lang.String sourceName, int lineno, java.lang.Object securityDomain) Compile a JavaScript function.The function source must be a function definition as defined by ECMA (e.g., "function f(a) { return a; }"). - Parameters:
- scope- the scope to compile relative to
- source- the function definition source
- sourceName- a string describing the source, such as a filename
- lineno- the starting line number
- securityDomain- an arbitrary object that specifies security information about the origin or owner of the script. For implementations that don't care about security, this value may be null.
- Returns:
- a Function that may later be called
- See Also:
- Function
 
 - 
decompileScriptpublic final java.lang.String decompileScript(Script script, int indent) Decompile the script.The canonical source of the script is returned. - Parameters:
- script- the script to decompile
- indent- the number of spaces to indent the result
- Returns:
- a string representing the script source
 
 - 
decompileFunctionpublic final java.lang.String decompileFunction(Function fun, int indent) Decompile a JavaScript Function.Decompiles a previously compiled JavaScript function object to canonical source. Returns function body of '[native code]' if no decompilation information is available. - Parameters:
- fun- the JavaScript function to decompile
- indent- the number of spaces to indent the result
- Returns:
- a string representing the function source
 
 - 
decompileFunctionBodypublic final java.lang.String decompileFunctionBody(Function fun, int indent) Decompile the body of a JavaScript Function.Decompiles the body a previously compiled JavaScript Function object to canonical source, omitting the function header and trailing brace. Returns '[native code]' if no decompilation information is available. - Parameters:
- fun- the JavaScript function to decompile
- indent- the number of spaces to indent the result
- Returns:
- a string representing the function body source.
 
 - 
newObjectpublic Scriptable newObject(Scriptable scope) Create a new JavaScript object.Equivalent to evaluating "new Object()". - Parameters:
- scope- the scope to search for the constructor and to evaluate against
- Returns:
- the new object
 
 - 
newObjectpublic Scriptable newObject(Scriptable scope, java.lang.String constructorName) Create a new JavaScript object by executing the named constructor.The call newObject(scope, "Foo")is equivalent to evaluating "new Foo()".- Parameters:
- scope- the scope to search for the constructor and to evaluate against
- constructorName- the name of the constructor to call
- Returns:
- the new object
 
 - 
newObjectpublic Scriptable newObject(Scriptable scope, java.lang.String constructorName, java.lang.Object[] args) Creates a new JavaScript object by executing the named constructor.Searches scopefor the named constructor, calls it with the given arguments, and returns the result.The code Object[] args = { "a", "b" }; newObject(scope, "Foo", args)is equivalent to evaluating "new Foo('a', 'b')", assuming that the Foo constructor has been defined inscope.- Parameters:
- scope- The scope to search for the constructor and to evaluate against
- constructorName- the name of the constructor to call
- args- the array of arguments for the constructor
- Returns:
- the new object
 
 - 
newArraypublic Scriptable newArray(Scriptable scope, int length) Create an array with a specified initial length.- Parameters:
- scope- the scope to create the object in
- length- the initial length (JavaScript arrays may have additional properties added dynamically).
- Returns:
- the new array object
 
 - 
newArraypublic Scriptable newArray(Scriptable scope, java.lang.Object[] elements) Create an array with a set of initial elements.- Parameters:
- scope- the scope to create the object in.
- elements- the initial elements. Each object in this array must be an acceptable JavaScript type and type of array should be exactly Object[], not SomeObjectSubclass[].
- Returns:
- the new array object.
 
 - 
getElementspublic final java.lang.Object[] getElements(Scriptable object) Get the elements of a JavaScript array.If the object defines a length property convertible to double number, then the number is converted Uint32 value as defined in Ecma 9.6 and Java array of that size is allocated. The array is initialized with the values obtained by calling get() on object for each value of i in [0,length-1]. If there is not a defined value for a property the Undefined value is used to initialize the corresponding element in the array. The Java array is then returned. If the object doesn't define a length property or it is not a number, empty array is returned. - Parameters:
- object- the JavaScript array or array-like object
- Returns:
- a Java array of objects
- Since:
- 1.4 release 2
 
 - 
toBooleanpublic static boolean toBoolean(java.lang.Object value) Convert the value to a JavaScript boolean value.See ECMA 9.2. - Parameters:
- value- a JavaScript value
- Returns:
- the corresponding boolean value converted using the ECMA rules
 
 - 
toNumberpublic static double toNumber(java.lang.Object value) Convert the value to a JavaScript Number value.Returns a Java double for the JavaScript Number. See ECMA 9.3. - Parameters:
- value- a JavaScript value
- Returns:
- the corresponding double value converted using the ECMA rules
 
 - 
toStringpublic static java.lang.String toString(java.lang.Object value) Convert the value to a JavaScript String value.See ECMA 9.8. - Parameters:
- value- a JavaScript value
- Returns:
- the corresponding String value converted using the ECMA rules
 
 - 
toObjectpublic static Scriptable toObject(java.lang.Object value, Scriptable scope) Convert the value to an JavaScript object value.Note that a scope must be provided to look up the constructors for Number, Boolean, and String. See ECMA 9.9. Additionally, arbitrary Java objects and classes will be wrapped in a Scriptable object with its Java fields and methods reflected as JavaScript properties of the object. - Parameters:
- value- any Java object
- scope- global scope containing constructors for Number, Boolean, and String
- Returns:
- new JavaScript object
 
 - 
toObject@Deprecated public static Scriptable toObject(java.lang.Object value, Scriptable scope, java.lang.Class<?> staticType) Deprecated.- See Also:
- toObject(Object, Scriptable)
 
 - 
javaToJSpublic static java.lang.Object javaToJS(java.lang.Object value, Scriptable scope)Convenient method to convert java value to its closest representation in JavaScript.If value is an instance of String, Number, Boolean, Function or Scriptable, it is returned as it and will be treated as the corresponding JavaScript type of string, number, boolean, function and object. Note that for Number instances during any arithmetic operation in JavaScript the engine will always use the result of Number.doubleValue()resulting in a precision loss if the number can not fit into double.If value is an instance of Character, it will be converted to string of length 1 and its JavaScript type will be string. The rest of values will be wrapped as LiveConnect objects by calling WrapFactory.wrap(Context cx, Scriptable scope, Object obj, Class staticType)as in:Context cx = Context.getCurrentContext(); return cx.getWrapFactory().wrap(cx, scope, value, null);- Parameters:
- value- any Java object
- scope- top scope object
- Returns:
- value suitable to pass to any API that takes JavaScript values.
 
 - 
javaToJSpublic static java.lang.Object javaToJS(java.lang.Object value, Scriptable scope, Context cx)Convenient method to convert java value to its closest representation in JavaScript.If value is an instance of String, Number, Boolean, Function or Scriptable, it is returned as it and will be treated as the corresponding JavaScript type of string, number, boolean, function and object. Note that for Number instances during any arithmetic operation in JavaScript the engine will always use the result of Number.doubleValue()resulting in a precision loss if the number can not fit into double.If value is an instance of Character, it will be converted to string of length 1 and its JavaScript type will be string. The rest of values will be wrapped as LiveConnect objects by calling WrapFactory.wrap(Context cx, Scriptable scope, Object obj, Class staticType)as in:return cx.getWrapFactory().wrap(cx, scope, value, null);- Parameters:
- value- any Java object
- scope- top scope object
- cx- context to use for wrapping LiveConnect objects
- Returns:
- value suitable to pass to any API that takes JavaScript values.
 
 - 
jsToJavapublic static java.lang.Object jsToJava(java.lang.Object value, java.lang.Class<?> desiredType) throws EvaluatorExceptionConvert a JavaScript value into the desired type. Uses the semantics defined with LiveConnect3 and throws an Illegal argument exception if the conversion cannot be performed.- Parameters:
- value- the JavaScript value to convert
- desiredType- the Java type to convert to. Primitive Java types are represented using the TYPE fields in the corresponding wrapper class in java.lang.
- Returns:
- the converted value
- Throws:
- EvaluatorException- if the conversion cannot be performed
 
 - 
toType@Deprecated public static java.lang.Object toType(java.lang.Object value, java.lang.Class<?> desiredType) throws java.lang.IllegalArgumentExceptionDeprecated.- Throws:
- java.lang.IllegalArgumentException- if the conversion cannot be performed. Note that- jsToJava(Object, Class)throws- EvaluatorExceptioninstead.
- See Also:
- jsToJava(Object, Class)
 
 - 
getJavaToJSONConverterpublic java.util.function.UnaryOperator<java.lang.Object> getJavaToJSONConverter() Returns the javaToJSONConverter for this Context.The converter is used by the JSON.stringify method for Java objects other than instances of Map,Collection, orObject[].The default converter if unset will convert Java Objects to their toString() value. - Returns:
- javaToJSONConverter for this Context
 
 - 
setJavaToJSONConverterpublic void setJavaToJSONConverter(java.util.function.UnaryOperator<java.lang.Object> javaToJSONConverter) throws java.lang.IllegalArgumentExceptionSets the javaToJSONConverter for this Context.The converter is used by the JSON.stringify method for Java objects other than instances of Map,Collection, orObject[].Objects returned by the converter will converted with javaToJS(Object, Scriptable)and then stringified themselves.- Parameters:
- javaToJSONConverter-
- Throws:
- java.lang.IllegalArgumentException- if javaToJSONConverter is null
 
 - 
throwAsScriptRuntimeExpublic static java.lang.RuntimeException throwAsScriptRuntimeEx(java.lang.Throwable e) Rethrow the exception wrapping it as the script runtime exception. Unless the exception is instance ofEcmaErrororEvaluatorExceptionit will be wrapped asWrappedException, a subclass ofEvaluatorException. The resulting exception object always contains source name and line number of script that triggered exception.This method always throws an exception, its return value is provided only for convenience to allow a usage like: throw Context.throwAsScriptRuntimeEx(ex); to indicate that code after the method is unreachable.- Throws:
- EvaluatorException
- EcmaError
 
 - 
isGeneratingDebugpublic final boolean isGeneratingDebug() Tell whether debug information is being generated.- Since:
- 1.3
 
 - 
setGeneratingDebugpublic final void setGeneratingDebug(boolean generatingDebug) Specify whether or not debug information should be generated.Setting the generation of debug information on will set the optimization level to zero. - Since:
- 1.3
 
 - 
isGeneratingSourcepublic final boolean isGeneratingSource() Tell whether source information is being generated.- Since:
- 1.3
 
 - 
setGeneratingSourcepublic final void setGeneratingSource(boolean generatingSource) Specify whether or not source information should be generated.Without source information, evaluating the "toString" method on JavaScript functions produces only "[native code]" for the body of the function. Note that code generated without source is not fully ECMA conformant. - Since:
- 1.3
 
 - 
getOptimizationLevelpublic final int getOptimizationLevel() Get the current optimization level.The optimization level is expressed as an integer between -1 and 9. - Since:
- 1.3
 
 - 
setOptimizationLevelpublic final void setOptimizationLevel(int optimizationLevel) Set the current optimization level.The optimization level is expected to be an integer between -1 and 9. Any negative values will be interpreted as -1, and any values greater than 9 will be interpreted as 9. An optimization level of -1 indicates that interpretive mode will always be used. Levels 0 through 9 indicate that class files may be generated. Higher optimization levels trade off compile time performance for runtime performance. The optimizer level can't be set greater than -1 if the optimizer package doesn't exist at run time. - Parameters:
- optimizationLevel- an integer indicating the level of optimization to perform
- Since:
- 1.3
 
 - 
isValidOptimizationLevelpublic static boolean isValidOptimizationLevel(int optimizationLevel) 
 - 
checkOptimizationLevelpublic static void checkOptimizationLevel(int optimizationLevel) 
 - 
getMaximumInterpreterStackDepthpublic final int getMaximumInterpreterStackDepth() Returns the maximum stack depth (in terms of number of call frames) allowed in a single invocation of interpreter. If the set depth would be exceeded, the interpreter will throw an EvaluatorException in the script. Defaults to Integer.MAX_VALUE. The setting only has effect for interpreted functions (those compiled with optimization level set to -1). As the interpreter doesn't use the Java stack but rather manages its own stack in the heap memory, a runaway recursion in interpreted code would eventually consume all available memory and cause OutOfMemoryError instead of a StackOverflowError limited to only a single thread. This setting helps prevent such situations.- Returns:
- The current maximum interpreter stack depth.
 
 - 
setMaximumInterpreterStackDepthpublic final void setMaximumInterpreterStackDepth(int max) Sets the maximum stack depth (in terms of number of call frames) allowed in a single invocation of interpreter. If the set depth would be exceeded, the interpreter will throw an EvaluatorException in the script. Defaults to Integer.MAX_VALUE. The setting only has effect for interpreted functions (those compiled with optimization level set to -1). As the interpreter doesn't use the Java stack but rather manages its own stack in the heap memory, a runaway recursion in interpreted code would eventually consume all available memory and cause OutOfMemoryError instead of a StackOverflowError limited to only a single thread. This setting helps prevent such situations.- Parameters:
- max- the new maximum interpreter stack depth
- Throws:
- java.lang.IllegalStateException- if this context's optimization level is not -1
- java.lang.IllegalArgumentException- if the new depth is not at least 1
 
 - 
setSecurityControllerpublic final void setSecurityController(SecurityController controller) Set the security controller for this context.SecurityController may only be set if it is currently null and SecurityController.hasGlobal()isfalse. Otherwise a SecurityException is thrown.- Parameters:
- controller- a SecurityController object
- Throws:
- java.lang.SecurityException- if there is already a SecurityController object for this Context or globally installed.
- See Also:
- SecurityController.initGlobal(SecurityController controller),- SecurityController.hasGlobal()
 
 - 
setClassShutterpublic final void setClassShutter(ClassShutter shutter) Set the LiveConnect access filter for this context.ClassShuttermay only be set if it is currently null. Otherwise a SecurityException is thrown.- Parameters:
- shutter- a ClassShutter object
- Throws:
- java.lang.SecurityException- if there is already a ClassShutter object for this Context
 
 - 
getClassShutterSetterpublic final Context.ClassShutterSetter getClassShutterSetter() 
 - 
getThreadLocalpublic final java.lang.Object getThreadLocal(java.lang.Object key) Get a value corresponding to a key.Since the Context is associated with a thread it can be used to maintain values that can be later retrieved using the current thread. Note that the values are maintained with the Context, so if the Context is disassociated from the thread the values cannot be retrieved. Also, if private data is to be maintained in this manner the key should be a java.lang.Object whose reference is not divulged to untrusted code. - Parameters:
- key- the key used to lookup the value
- Returns:
- a value previously stored using putThreadLocal.
 
 - 
putThreadLocalpublic final void putThreadLocal(java.lang.Object key, java.lang.Object value)Put a value that can later be retrieved using a given key.- Parameters:
- key- the key used to index the value
- value- the value to save
 
 - 
removeThreadLocalpublic final void removeThreadLocal(java.lang.Object key) Remove values from thread-local storage.- Parameters:
- key- the key for the entry to remove.
- Since:
- 1.5 release 2
 
 - 
setCachingEnabled@Deprecated public static void setCachingEnabled(boolean cachingEnabled) Deprecated.
 - 
setWrapFactorypublic final void setWrapFactory(WrapFactory wrapFactory) Set a WrapFactory for this Context.The WrapFactory allows custom object wrapping behavior for Java object manipulated with JavaScript. - Since:
- 1.5 Release 4
- See Also:
- WrapFactory
 
 - 
getWrapFactorypublic final WrapFactory getWrapFactory() Return the current WrapFactory, or null if none is defined.- Since:
- 1.5 Release 4
- See Also:
- WrapFactory
 
 - 
getDebuggerpublic final Debugger getDebugger() Return the current debugger.- Returns:
- the debugger, or null if none is attached.
 
 - 
getDebuggerContextDatapublic final java.lang.Object getDebuggerContextData() Return the debugger context data associated with current context.- Returns:
- the debugger data, or null if debugger is not attached
 
 - 
setDebuggerpublic final void setDebugger(Debugger debugger, java.lang.Object contextData) Set the associated debugger.- Parameters:
- debugger- the debugger to be used on callbacks from the engine.
- contextData- arbitrary object that debugger can use to store per Context data.
 
 - 
getDebuggableViewpublic static DebuggableScript getDebuggableView(Script script) Return DebuggableScript instance if any associated with the script. If callable supports DebuggableScript implementation, the method returns it. Otherwise null is returned.
 - 
hasFeaturepublic boolean hasFeature(int featureIndex) Controls certain aspects of script semantics. Should be overwritten to alter default behavior.The default implementation calls ContextFactory.hasFeature(Context cx, int featureIndex)that allows to customize Context behavior without introducing Context subclasses.ContextFactorydocumentation gives an example of hasFeature implementation.- Parameters:
- featureIndex- feature index to check
- Returns:
- true if the featureIndexfeature is turned on
- See Also:
- FEATURE_NON_ECMA_GET_YEAR,- FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME,- FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER,- FEATURE_TO_STRING_AS_SOURCE,- FEATURE_PARENT_PROTO_PROPRTIES,- FEATURE_E4X,- FEATURE_DYNAMIC_SCOPE,- FEATURE_STRICT_VARS,- FEATURE_STRICT_EVAL,- FEATURE_LOCATION_INFORMATION_IN_ERROR,- FEATURE_STRICT_MODE,- FEATURE_WARNING_AS_ERROR,- FEATURE_ENHANCED_JAVA_ACCESS
 
 - 
getE4xImplementationFactorypublic XMLLib.Factory getE4xImplementationFactory() Returns an object which specifies an E4X implementation to use within thisContext. Note that the XMLLib.Factory interface should be considered experimental.The default implementation uses the implementation provided by this Context'sContextFactory.- Returns:
- An XMLLib.Factory. Should not return nullifFEATURE_E4Xis enabled. SeehasFeature(int).
 
 - 
getInstructionObserverThresholdpublic final int getInstructionObserverThreshold() Get threshold of executed instructions counter that triggers call toobserveInstructionCount(). When the threshold is zero, instruction counting is disabled, otherwise each time the run-time executes at least the threshold value of script instructions,observeInstructionCount()will be called.
 - 
setInstructionObserverThresholdpublic final void setInstructionObserverThreshold(int threshold) Set threshold of executed instructions counter that triggers call toobserveInstructionCount(). When the threshold is zero, instruction counting is disabled, otherwise each time the run-time executes at least the threshold value of script instructions,observeInstructionCount()will be called.
 Note that the meaning of "instruction" is not guaranteed to be consistent between compiled and interpretive modes: executing a given script or function in the different modes will result in different instruction counts against the threshold.setGenerateObserverCount(boolean)is called with true ifthresholdis greater than zero, false otherwise.- Parameters:
- threshold- The instruction threshold
 
 - 
setGenerateObserverCountpublic void setGenerateObserverCount(boolean generateObserverCount) Turn on or off generation of code with callbacks to track the count of executed instructions. Currently only affects JVM byte code generation: this slows down the generated code, but code generated without the callbacks will not be counted toward instruction thresholds. Rhino's interpretive mode does instruction counting without inserting callbacks, so there is no requirement to compile code differently.- Parameters:
- generateObserverCount- if true, generated code will contain calls to accumulate an estimate of the instructions executed.
 
 - 
observeInstructionCountprotected void observeInstructionCount(int instructionCount) Allow application to monitor counter of executed script instructions in Context subclasses. Run-time calls this when instruction counting is enabled and the counter reaches limit set bysetInstructionObserverThreshold(). The method is useful to observe long running scripts and if necessary to terminate them.The default implementation calls ContextFactory.observeInstructionCount(Context cx, int instructionCount)that allows to customize Context behavior without introducing Context subclasses.- Parameters:
- instructionCount- amount of script instruction executed since last call to- observeInstructionCount
- Throws:
- java.lang.Error- to terminate the script
- See Also:
- setOptimizationLevel(int)
 
 - 
createClassLoaderpublic GeneratedClassLoader createClassLoader(java.lang.ClassLoader parent) Create class loader for generated classes. The method callsContextFactory.createClassLoader(ClassLoader)using the result ofgetFactory().
 - 
getApplicationClassLoaderpublic final java.lang.ClassLoader getApplicationClassLoader() 
 - 
setApplicationClassLoaderpublic final void setApplicationClassLoader(java.lang.ClassLoader loader) 
 - 
enqueueMicrotaskpublic void enqueueMicrotask(java.lang.Runnable task) Add a task that will be executed at the end of the current operation. The various "evaluate" functions will all call this before exiting to ensure that all microtasks run to completion. Otherwise, callers should call "processMicrotasks" to run them all. This feature is primarily used to implement Promises. The microtask queue is not thread-safe.
 - 
processMicrotaskspublic void processMicrotasks() Run all the microtasks for the current context to completion. This is called by the various "evaluate" functions. Frameworks that call Function objects directly should call this function to ensure that everything completes if they want all Promises to eventually resolve. This function is idempotent, but the microtask queue is not thread-safe.
 - 
setTrackUnhandledPromiseRejectionspublic void setTrackUnhandledPromiseRejections(boolean track) Control whether to track unhandled promise rejections. If "track" is set to true, then the tracker returned by "getUnhandledPromiseTracker" must be periodically used to process the queue of unhandled promise rejections, or a memory leak may result.- Parameters:
- track- if true, then track unhandled promise rejections
 
 - 
getUnhandledPromiseTrackerpublic UnhandledRejectionTracker getUnhandledPromiseTracker() Return the object used to track unhandled promise rejections.- Returns:
- the tracker object
 
 - 
compileImplprotected java.lang.Object compileImpl(Scriptable scope, java.lang.String sourceString, java.lang.String sourceName, int lineno, java.lang.Object securityDomain, boolean returnFunction, Evaluator compiler, ErrorReporter compilationErrorReporter) throws java.io.IOException - Throws:
- java.io.IOException
 
 - 
isGeneratingDebugChangedpublic final boolean isGeneratingDebugChanged() 
 - 
addActivationNamepublic void addActivationName(java.lang.String name) Add a name to the list of names forcing the creation of real activation objects for functions.- Parameters:
- name- the name of the object to add to the list
 
 - 
isActivationNeededpublic final boolean isActivationNeeded(java.lang.String name) Check whether the name is in the list of names of objects forcing the creation of activation objects.- Parameters:
- name- the name of the object to test
- Returns:
- true if an function activation object is needed.
 
 - 
removeActivationNamepublic void removeActivationName(java.lang.String name) Remove a name from the list of names forcing the creation of real activation objects for functions.- Parameters:
- name- the name of the object to remove from the list
 
 - 
isStrictModepublic final boolean isStrictMode() 
 - 
isCurrentContextStrictpublic static boolean isCurrentContextStrict() 
 
- 
 
-