Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
   /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
    *
    * This Source Code Form is subject to the terms of the Mozilla Public
    * License, v. 2.0. If a copy of the MPL was not distributed with this
    * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
   
   // API class
   
   package org.mozilla.javascript;
  
  import java.io.Reader;
  import java.io.Writer;
  import java.util.Map;
  import java.util.HashMap;
  import java.util.Set;
  import java.util.HashSet;
  import java.util.Locale;
  
This 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(org.mozilla.javascript.ContextAction) or enter() 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.

Author(s):
Norris Boyd
Brendan Eich
See also:
Scriptable
  
  
  public class Context
  {
    
Language versions. All integral values are reserved for future version numbers.
  

    
The unknown version.
  
      public static final int VERSION_UNKNOWN =   -1;

    
The default version.
  
      public static final int VERSION_DEFAULT =    0;

    
JavaScript 1.0
  
      public static final int VERSION_1_0 =      100;

    
JavaScript 1.1
  
      public static final int VERSION_1_1 =      110;

    
JavaScript 1.2
  
      public static final int VERSION_1_2 =      120;

    
JavaScript 1.3
  
      public static final int VERSION_1_3 =      130;

    
JavaScript 1.4
  
      public static final int VERSION_1_4 =      140;

    
JavaScript 1.5
 
     public static final int VERSION_1_5 =      150;

    
JavaScript 1.6
 
     public static final int VERSION_1_6 =      160;

    
JavaScript 1.7
 
     public static final int VERSION_1_7 =      170;

    
JavaScript 1.8
 
     public static final int VERSION_1_8 =      180;

    
Controls behaviour of Date.prototype.getYear(). If hasFeature(FEATURE_NON_ECMA_GET_YEAR) returns true, Date.prototype.getYear subtructs 1900 only if 1900 <= date < 2000. The default behavior of hasFeature(int) is always to subtruct 1900 as rquired by ECMAScript B.2.4.
 
     public static final int FEATURE_NON_ECMA_GET_YEAR = 1;

    
Control if member expression as function name extension is available. If hasFeature(FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME) returns true, allow function memberExpression(args) { body } to be syntax sugar for memberExpression = function(args) { body }, when memberExpression is not a simple identifier. See ECMAScript-262, section 11.2 for definition of memberExpression. By default hasFeature(int) returns false.
 
     public static final int FEATURE_MEMBER_EXPR_AS_FUNCTION_NAME = 2;

    
Control if reserved keywords are treated as identifiers. If hasFeature(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.
 
     public static final int FEATURE_RESERVED_KEYWORD_AS_IDENTIFIER = 3;

    
Control if toString() should returns the same result as toSource() when applied to objects and arrays. If hasFeature(FEATURE_TO_STRING_AS_SOURCE) returns true, calling toString() on JS objects gives the same result as calling toSource(). 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 to VERSION_1_2.

 
     public static final int FEATURE_TO_STRING_AS_SOURCE = 4;

    
Control if properties __proto__ and __parent__ are treated specially. If hasFeature(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__ = y changes the prototype chain of the object x to point to y, x["__proto__"] = y simply assigns a new value to the property __proto__ in x even when the feature is on. By default hasFeature(int) returns true.

 
     public static final int FEATURE_PARENT_PROTO_PROPERTIES = 5;

        

Deprecated:
In previous releases, this name was given to FEATURE_PARENT_PROTO_PROPERTIES.
 
     public static final int FEATURE_PARENT_PROTO_PROPRTIES = 5;

    
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 to VERSION_DEFAULT or is at least VERSION_1_6.

Since:
1.6 Release 1
 
     public static final int FEATURE_E4X = 6;

    
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
 
     public static final int FEATURE_DYNAMIC_SCOPE = 7;

    
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
 
     public static final int FEATURE_STRICT_VARS = 8;

    
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
 
     public static final int FEATURE_STRICT_EVAL = 9;

    
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
 
     public static final int FEATURE_LOCATION_INFORMATION_IN_ERROR = 10;

    
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
 
     public static final int FEATURE_STRICT_MODE = 11;

    
Controls whether a warning should be treated as an error.

Since:
1.6 Release 6
 
     public static final int FEATURE_WARNING_AS_ERROR = 12;

    
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
 
     public static final int FEATURE_ENHANCED_JAVA_ACCESS = 13;
 
     public static final String languageVersionProperty = "language version";
     public static final String errorReporterProperty   = "error reporter";

    
Convenient value to use as zero-length array of objects.
 
     public static final Object[] emptyArgs = .;

    
Creates a new Context. The context will be associated with the ContextFactory.getGlobal(). Note that the Context must be associated with a thread before it can be used to execute a script.

Deprecated:
this constructor is deprecated because it creates a dependency on a static singleton context factory. Use ContextFactory.enter() or ContextFactory.call(org.mozilla.javascript.ContextAction) instead. If you subclass this class, consider using Context(org.mozilla.javascript.ContextFactory) constructor instead in the subclasses' constructors.
 
     public Context()
     {
         this(ContextFactory.getGlobal());
     }

    
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.
 
     protected Context(ContextFactory factory)
     {
         if(factory == null) {
             throw new IllegalArgumentException("factory == null");
         }
         this. = factory;
          = ;
          =  != null ? 0 : -1;
     }

    
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(org.mozilla.javascript.ContextAction)
 
     public static Context getCurrentContext()
     {
         Object helper = ..getThreadContextHelper();
         return ..getContext(helper);
     }

    
Same as calling ContextFactory.enterContext() on the global ContextFactory instance.

Returns:
a Context associated with the current thread
See also:
getCurrentContext()
exit()
call(org.mozilla.javascript.ContextAction)
 
     public static Context enter()
     {
         return enter(null);
     }

    
Get a Context associated with the current thread, using the given Context if need be.

The same as enter() except that cx is associated with the current thread and returned if the current thread has no associated context and cx is not associated with any other thread.

Deprecated:
use ContextFactory.enterContext(org.mozilla.javascript.Context) instead as this method relies on usage of a static singleton "global" ContextFactory.
Parameters:
cx a Context to associate with the thread if possible
Returns:
a Context associated with the current thread
See also:
ContextFactory.enterContext(org.mozilla.javascript.Context)
ContextFactory.call(org.mozilla.javascript.ContextAction)
 
     public static Context enter(Context cx)
     {
         return enter(cx, ContextFactory.getGlobal());
     }
 
     static final Context enter(Context cxContextFactory factory)
     {
         Object helper = ..getThreadContextHelper();
         Context old = ..getContext(helper);
         if (old != null) {
             cx = old;
         } else {
             if (cx == null) {
                 cx = factory.makeContext();
                 if (cx.enterCount != 0) {
                     throw new IllegalStateException("factory.makeContext() returned Context instance already associated with some thread");
                 }
                 factory.onContextCreated(cx);
                 if (factory.isSealed() && !cx.isSealed()) {
                     cx.seal(null);
                 }
             } else {
                 if (cx.enterCount != 0) {
                     throw new IllegalStateException("can not use Context instance already associated with some thread");
                 }
             }
             ..setContext(helpercx);
         }
         ++cx.enterCount;
         return cx;
      }

    
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 to ContextFactory.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.

 
     public static void exit()
     {
         Object helper = ..getThreadContextHelper();
         Context cx = ..getContext(helper);
         if (cx == null) {
             throw new IllegalStateException(
                 "Calling Context.exit without previous Context.enter");
         }
         if (cx.enterCount < 1) Kit.codeBug();
         if (--cx.enterCount == 0) {
             ..setContext(helpernull);
             cx.factory.onContextReleased(cx);
         }
     }

    
Call ContextAction.run(org.mozilla.javascript.Context) using the Context instance associated with the current thread. If no Context is associated with the thread, then ContextFactory.getGlobal().makeContext() will be called to construct new Context instance. The instance will be temporary associated with the thread during call to ContextAction.run(org.mozilla.javascript.Context).

Deprecated:
use ContextFactory.call(org.mozilla.javascript.ContextAction) instead as this method relies on usage of a static singleton "global" ContextFactory.
Returns:
The result of ContextAction.run(org.mozilla.javascript.Context).
 
     public static Object call(ContextAction action)
     {
         return call(ContextFactory.getGlobal(), action);
     }

    
Call Callable.call(org.mozilla.javascript.Context,org.mozilla.javascript.Scriptable,org.mozilla.javascript.Scriptable,java.lang.Object[]) using the Context instance associated with the current thread. If no Context is associated with the thread, then ContextFactory.makeContext() will be called to construct new Context instance. The instance will be temporary associated with the thread during call to ContextAction.run(org.mozilla.javascript.Context).

It is allowed but not advisable to use null for factory argument in which case the global static singleton ContextFactory instance will be used to create new context instances.

 
     public static Object call(ContextFactory factoryfinal Callable callable,
                               final Scriptable scopefinal Scriptable thisObj,
                               final Object[] args)
     {
         if(factory == null) {
             factory = ContextFactory.getGlobal();
         }
         return call(factorynew ContextAction() {
             public Object run(Context cx) {
                 return callable.call(cxscopethisObjargs);
             }
         });
     }

    
 
     static Object call(ContextFactory factoryContextAction action) {
         Context cx = enter(nullfactory);
         try {
             return action.run(cx);
         }
         finally {
             exit();
         }
     }

    
 
     public static void addContextListener(ContextListener listener)
     {
         // Special workaround for the debugger
         String DBG = "org.mozilla.javascript.tools.debugger.Main";
         if (DBG.equals(listener.getClass().getName())) {
             Class<?> cl = listener.getClass();
             Class<?> factoryClass = Kit.classOrNull(
                 "org.mozilla.javascript.ContextFactory");
             Class<?>[] sig = { factoryClass };
             Object[] args = { ContextFactory.getGlobal() };
             try {
                 Method m = cl.getMethod("attachTo"sig);
                 m.invoke(listenerargs);
             } catch (Exception ex) {
                 RuntimeException rex = new RuntimeException();
                 Kit.initCause(rexex);
                 throw rex;
             }
             return;
         }
 
         ContextFactory.getGlobal().addListener(listener);
     }

    
 
     public static void removeContextListener(ContextListener listener)
     {
         ContextFactory.getGlobal().addListener(listener);
     }

    
Return ContextFactory instance used to create this Context.
 
     public final ContextFactory getFactory()
     {
         return ;
     }

    
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.

 
     public final boolean isSealed()
     {
         return ;
     }

    
Seal this Context object so any attempt to modify any of its properties including calling enter() and exit() methods will throw an exception.

If sealKey is not null, calling unseal(java.lang.Object) with the same key unseals the object. If sealKey is null, unsealing is no longer possible.

 
     public final void seal(Object sealKey)
     {
         if (onSealedMutation();
          = true;
         this. = sealKey;
     }

    
Unseal previously sealed Context object. The sealKey argument should not be null and should match sealKey suplied with the last call to seal(java.lang.Object) or an exception will be thrown.

 
     public final void unseal(Object sealKey)
     {
         if (sealKey == nullthrow new IllegalArgumentException();
         if (this. != sealKeythrow new IllegalArgumentException();
         if (!throw new IllegalStateException();
          = false;
         this. = null;
     }
 
     static void onSealedMutation()
     {
         throw new IllegalStateException();
     }

    
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.
 
     public final int getLanguageVersion()
     {
        return ;
     }

    
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.
 
     public void setLanguageVersion(int version)
     {
         if (onSealedMutation();
         checkLanguageVersion(version);
         Object listeners = ;
         if (listeners != null && version != this.) {
             firePropertyChangeImpl(listeners,
                                Integer.valueOf(this.),
                                Integer.valueOf(version));
         }
         this. = version;
     }
 
     public static boolean isValidLanguageVersion(int version)
     {
         switch (version) {
             case :
             case :
             case :
             case :
             case :
             case :
             case :
             case :
             case :
             case :
                 return true;
         }
         return false;
     }
 
     public static void checkLanguageVersion(int version)
     {
         if (isValidLanguageVersion(version)) {
             return;
         }
         throw new IllegalArgumentException("Bad language version: "+version);
     }

    
Get the implementation version.

The implementation version is of the form

    "name langVer release relNum date"
 
where 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".

Returns:
a string that encodes the product, language version, release number, and date.
 
     public final String getImplementationVersion()
     {
         // XXX Probably it would be better to embed this directly into source
         // with special build preprocessing but that would require some ant
         // tweaking and then replacing token in resource files was simpler
         if ( == null) {
             
                 = ScriptRuntime.getMessage0("implementation.version");
         }
         return ;
     }

    
Get the current error reporter.

See also:
ErrorReporter
 
     public final ErrorReporter getErrorReporter()
     {
         if ( == null) {
             return .;
         }
         return ;
     }

    
Change the current error reporter.

Returns:
the previous error reporter
See also:
ErrorReporter
 
     public final ErrorReporter setErrorReporter(ErrorReporter reporter)
     {
         if (onSealedMutation();
         if (reporter == nullthrow new IllegalArgumentException();
         ErrorReporter old = getErrorReporter();
         if (reporter == old) {
             return old;
         }
         Object listeners = ;
         if (listeners != null) {
             firePropertyChangeImpl(listeners,
                                    oldreporter);
         }
         this. = reporter;
         return old;
     }

    
Get the current locale. Returns the default locale if none has been set.

 
 
     public final Locale getLocale()
     {
         if ( == null)
              = Locale.getDefault();
         return ;
     }

    
Set the current locale.

 
     public final Locale setLocale(Locale loc)
     {
         if (onSealedMutation();
         Locale result = ;
          = loc;
         return result;
     }

    
Register an object to receive notifications when a bound property has changed

 
     public final void addPropertyChangeListener(PropertyChangeListener l)
     {
         if (onSealedMutation();
          = Kit.addListener(l);
     }

    
Remove an object from the list of objects registered to receive notification of changes to a bounded property

 
     public final void removePropertyChangeListener(PropertyChangeListener l)
     {
         if (onSealedMutation();
          = Kit.removeListener(l);
     }

    
Notify any registered listeners that a bounded property has changed

 
     final void firePropertyChange(String propertyObject oldValue,
                                   Object newValue)
     {
         Object listeners = ;
         if (listeners != null) {
             firePropertyChangeImpl(listenerspropertyoldValuenewValue);
         }
     }
 
     private void firePropertyChangeImpl(Object listenersString property,
                                         Object oldValueObject newValue)
     {
         for (int i = 0; ; ++i) {
             Object l = Kit.getListener(listenersi);
             if (l == null)
                 break;
             if (l instanceof PropertyChangeListener) {
                 PropertyChangeListener pcl = (PropertyChangeListener)l;
                 pcl.propertyChange(new PropertyChangeEvent(
                     thispropertyoldValuenewValue));
             }
         }
     }

    
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
 
     public static void reportWarning(String messageString sourceName,
                                      int linenoString lineSource,
                                      int lineOffset)
     {
         Context cx = Context.getContext();
         if (cx.hasFeature())
             reportError(messagesourceNamelinenolineSourcelineOffset);
         else
             cx.getErrorReporter().warning(messagesourceNamelineno,
                                           lineSourcelineOffset);
     }

    
Report a warning using the error reporter for the current thread.

Parameters:
message the warning message to report
See also:
ErrorReporter
 
     public static void reportWarning(String message)
     {
         int[] linep = { 0 };
         String filename = getSourcePositionFromStack(linep);
         Context.reportWarning(messagefilenamelinep[0], null, 0);
     }
 
     public static void reportWarning(String messageThrowable t)
     {
         int[] linep = { 0 };
         String filename = getSourcePositionFromStack(linep);
         Writer sw = new StringWriter();
         PrintWriter pw = new PrintWriter(sw);
         pw.println(message);
         t.printStackTrace(pw);
         pw.flush();
         Context.reportWarning(sw.toString(), filenamelinep[0], null, 0);
     }

    
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
 
     public static void reportError(String messageString sourceName,
                                    int linenoString lineSource,
                                    int lineOffset)
     {
         Context cx = getCurrentContext();
         if (cx != null) {
             cx.getErrorReporter().error(messagesourceNamelineno,
                                         lineSourcelineOffset);
         } else {
             throw new EvaluatorException(messagesourceNamelineno,
                                          lineSourcelineOffset);
         }
     }

    
Report an error using the error reporter for the current thread.

Parameters:
message the error message to report
See also:
ErrorReporter
 
     public static void reportError(String message)
     {
         int[] linep = { 0 };
         String filename = getSourcePositionFromStack(linep);
         Context.reportError(messagefilenamelinep[0], null, 0);
     }

    
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
 
     public static EvaluatorException reportRuntimeError(String message,
                                                         String sourceName,
                                                         int lineno,
                                                         String lineSource,
                                                         int lineOffset)
     {
         Context cx = getCurrentContext();
         if (cx != null) {
             return cx.getErrorReporter().
                             runtimeError(messagesourceNamelineno,
                                          lineSourcelineOffset);
         } else {
             throw new EvaluatorException(messagesourceNamelineno,
                                          lineSourcelineOffset);
         }
     }
 
     static EvaluatorException reportRuntimeError0(String messageId)
     {
         String msg = ScriptRuntime.getMessage0(messageId);
         return reportRuntimeError(msg);
     }
 
     static EvaluatorException reportRuntimeError1(String messageId,
                                                   Object arg1)
     {
         String msg = ScriptRuntime.getMessage1(messageIdarg1);
         return reportRuntimeError(msg);
     }
 
     static EvaluatorException reportRuntimeError2(String messageId,
                                                   Object arg1Object arg2)
     {
         String msg = ScriptRuntime.getMessage2(messageIdarg1arg2);
         return reportRuntimeError(msg);
     }
 
     static EvaluatorException reportRuntimeError3(String messageId,
                                                   Object arg1Object arg2,
                                                   Object arg3)
     {
         String msg = ScriptRuntime.getMessage3(messageIdarg1arg2arg3);
         return reportRuntimeError(msg);
     }
 
     static EvaluatorException reportRuntimeError4(String messageId,
                                                   Object arg1Object arg2,
                                                   Object arg3Object arg4)
     {
         String msg
             = ScriptRuntime.getMessage4(messageIdarg1arg2arg3arg4);
         return reportRuntimeError(msg);
     }

    
Report a runtime error using the error reporter for the current thread.

Parameters:
message the error message to report
See also:
ErrorReporter
 
     public static EvaluatorException reportRuntimeError(String message)
     {
         int[] linep = { 0 };
         String filename = getSourcePositionFromStack(linep);
         return Context.reportRuntimeError(messagefilenamelinep[0], null, 0);
     }

    
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
 
     public final ScriptableObject initStandardObjects()
     {
         return initStandardObjects(nullfalse);
     }

    
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.
    public final Scriptable initStandardObjects(ScriptableObject scope)
    {
        return initStandardObjects(scopefalse);
    }

    
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
                                                boolean sealed)
    {
        return ScriptRuntime.initStandardObjects(thisscopesealed);
    }

    
Get the singleton object that represents the JavaScript Undefined value.
    public static Object getUndefinedValue()
    {
        return .;
    }

    
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
    public final Object evaluateString(Scriptable scopeString source,
                                       String sourceNameint lineno,
                                       Object securityDomain)
    {
        Script script = compileString(sourcesourceNamelineno,
                                      securityDomain);
        if (script != null) {
            return script.exec(thisscope);
        } else {
            return null;
        }
    }

    
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
    public final Object evaluateReader(Scriptable scopeReader in,
                                       String sourceNameint lineno,
                                       Object securityDomain)
        throws IOException
    {
        Script script = compileReader(scopeinsourceNamelineno,
                                      securityDomain);
        if (script != null) {
            return script.exec(thisscope);
        } else {
            return null;
        }
    }

    
Execute script that may pause execution by capturing a continuation. Caller must be prepared to catch a ContinuationPending exception and resume execution by calling resumeContinuation(java.lang.Object,org.mozilla.javascript.Scriptable,java.lang.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
            Scriptable scope)
        throws ContinuationPending
    {
        if (!(script instanceof InterpretedFunction) ||
            !((InterpretedFunction)script).isScript())
        {
            // Can only be applied to scripts
            throw new IllegalArgumentException("Script argument was not" +
                    " a script or was not created by interpreted mode ");
        }
        return callFunctionWithContinuations((InterpretedFunctionscript,
                scope.);
    }

    
Call function that may pause execution by capturing a continuation. Caller must be prepared to catch a ContinuationPending exception and resume execution by calling resumeContinuation(java.lang.Object,org.mozilla.javascript.Scriptable,java.lang.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
            Scriptable scopeObject[] args)
        throws ContinuationPending
    {
        if (!(function instanceof InterpretedFunction)) {
            // Can only be applied to scripts
            throw new IllegalArgumentException("Function argument was not" +
                    " created by interpreted mode ");
        }
        if (ScriptRuntime.hasTopCall(this)) {
            throw new IllegalStateException("Cannot have any pending top " +
                    "calls when executing a script with continuations");
        }
        // Annotate so we can check later to ensure no java code in
        // intervening frames
         = true;
        return ScriptRuntime.doTopCall(functionthisscopescopeargs);
    }

    
Capture a continuation from the current execution. The execution must have been started via a call to executeScriptWithContinuations(org.mozilla.javascript.Script,org.mozilla.javascript.Scriptable) or callFunctionWithContinuations(org.mozilla.javascript.Callable,org.mozilla.javascript.Scriptable,java.lang.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
        return new ContinuationPending(
                Interpreter.captureContinuation(this));
    }

    
Restarts execution of the JavaScript suspended at the call to captureContinuation(). 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
    public Object resumeContinuation(Object continuation,
            Scriptable scopeObject functionResult)
            throws ContinuationPending
    {
        Object[] args = { functionResult };
        return Interpreter.restartContinuation(
                (org.mozilla.javascript.NativeContinuationcontinuation,
                thisscopeargs);
    }

    
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
    public final boolean stringIsCompilableUnit(String source)
    {
        boolean errorseen = false;
        CompilerEnvirons compilerEnv = new CompilerEnvirons();
        compilerEnv.initFromContext(this);
        // no source name or source text manager, because we're just
        // going to throw away the result.
        compilerEnv.setGeneratingSource(false);
        Parser p = new Parser(compilerEnv.);
        try {
            p.parse(sourcenull, 1);
        } catch (EvaluatorException ee) {
            errorseen = true;
        }
        // Return false only if an error occurred as a result of reading past
        // the end of the file, i.e. if the source could be fixed by
        // appending more source.
        if (errorseen && p.eof())
            return false;
        else
            return true;
    }

    
    public final Script compileReader(Scriptable scopeReader in,
                                      String sourceNameint lineno,
                                      Object securityDomain)
        throws IOException
    {
        return compileReader(insourceNamelinenosecurityDomain);
    }

    
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
    public final Script compileReader(Reader inString sourceName,
                                      int linenoObject securityDomain)
        throws IOException
    {
        if (lineno < 0) {
            // For compatibility IllegalArgumentException can not be thrown here
            lineno = 0;
        }
        return (ScriptcompileImpl(nullinnullsourceNamelineno,
                                    securityDomainfalsenullnull);
    }

    
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
    public final Script compileString(String source,
                                      String sourceNameint lineno,
                                      Object securityDomain)
    {
        if (lineno < 0) {
            // For compatibility IllegalArgumentException can not be thrown here
            lineno = 0;
        }
        return compileString(sourcenullnullsourceNamelineno,
                             securityDomain);
    }
    final Script compileString(String source,
                               Evaluator compiler,
                               ErrorReporter compilationErrorReporter,
                               String sourceNameint lineno,
                               Object securityDomain)
    {
        try {
            return (ScriptcompileImpl(nullnullsourcesourceNamelineno,
                                        securityDomainfalse,
                                        compilercompilationErrorReporter);
        } catch (IOException ex) {
            // Should not happen when dealing with source as string
            throw new RuntimeException();
        }
    }

    
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
    public final Function compileFunction(Scriptable scopeString source,
                                          String sourceNameint lineno,
                                          Object securityDomain)
    {
        return compileFunction(scopesourcenullnullsourceNamelineno,
                               securityDomain);
    }
    final Function compileFunction(Scriptable scopeString source,
                                   Evaluator compiler,
                                   ErrorReporter compilationErrorReporter,
                                   String sourceNameint lineno,
                                   Object securityDomain)
    {
        try {
            return (FunctioncompileImpl(scopenullsourcesourceName,
                                          linenosecurityDomaintrue,
                                          compilercompilationErrorReporter);
        }
        catch (IOException ioe) {
            // Should never happen because we just made the reader
            // from a String
            throw new RuntimeException();
        }
    }

    
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
    public final String decompileScript(Script scriptint indent)
    {
        NativeFunction scriptImpl = (NativeFunctionscript;
        return scriptImpl.decompile(indent, 0);
    }

    
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
    public final String decompileFunction(Function funint indent)
    {
        if (fun instanceof BaseFunction)
            return ((BaseFunction)fun).decompile(indent, 0);
        else
            return "function " + fun.getClassName() +
                   "() {\n\t[native code]\n}\n";
    }

    
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.
    public final String decompileFunctionBody(Function funint indent)
    {
        if (fun instanceof BaseFunction) {
            BaseFunction bf = (BaseFunction)fun;
            return bf.decompile(indent.);
        }
        // ALERT: not sure what the right response here is.
        return "[native code]\n";
    }

    
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
    public Scriptable newObject(Scriptable scope)
    {
        NativeObject result = new NativeObject();
        ScriptRuntime.setBuiltinProtoAndParent(resultscope,
                ..);
        return result;
    }

    
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
    public Scriptable newObject(Scriptable scopeString constructorName)
    {
        return newObject(scopeconstructorName.);
    }

    
Creates a new JavaScript object by executing the named constructor. Searches scope for 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 in scope.

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
    public Scriptable newObject(Scriptable scopeString constructorName,
                                Object[] args)
    {
        scope = ScriptableObject.getTopLevelScope(scope);
        Function ctor = ScriptRuntime.getExistingCtor(thisscope,
                                                      constructorName);
        if (args == null) { args = .; }
        return ctor.construct(thisscopeargs);
    }

    
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
    public Scriptable newArray(Scriptable scopeint length)
    {
        NativeArray result = new NativeArray(length);
        ScriptRuntime.setBuiltinProtoAndParent(resultscope,
                ..);
        return result;
    }

    
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.
    public Scriptable newArray(Scriptable scopeObject[] elements)
    {
        if (elements.getClass().getComponentType() != .)
            throw new IllegalArgumentException();
        NativeArray result = new NativeArray(elements);
        ScriptRuntime.setBuiltinProtoAndParent(resultscope,
                ..);
        return result;
    }

    
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
    public final Object[] getElements(Scriptable object)
    {
        return ScriptRuntime.getArrayElements(object);
    }

    
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
    public static boolean toBoolean(Object value)
    {
        return ScriptRuntime.toBoolean(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
    public static double toNumber(Object value)
    {
        return ScriptRuntime.toNumber(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
    public static String toString(Object value)
    {
        return ScriptRuntime.toString(value);
    }

    
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
    public static Scriptable toObject(Object valueScriptable scope)
    {
        return ScriptRuntime.toObject(scopevalue);
    }

    
    public static Scriptable toObject(Object valueScriptable scope,
                                      Class<?> staticType)
    {
        return ScriptRuntime.toObject(scopevalue);
    }

    
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(org.mozilla.javascript.Context,org.mozilla.javascript.Scriptable,java.lang.Object,java.lang.Class) 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.
    public static Object javaToJS(Object valueScriptable scope)
    {
        if (value instanceof String || value instanceof Number
            || value instanceof Boolean || value instanceof Scriptable)
        {
            return value;
        } else if (value instanceof Character) {
            return String.valueOf(((Character)value).charValue());
        } else {
            Context cx = Context.getContext();
            return cx.getWrapFactory().wrap(cxscopevaluenull);
        }
    }

    
Convert 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
    public static Object jsToJava(Object valueClass<?> desiredType)
        throws EvaluatorException
    {
        return NativeJavaObject.coerceTypeImpl(desiredTypevalue);
    }

    

Deprecated:
Throws:
java.lang.IllegalArgumentException if the conversion cannot be performed. Note that jsToJava(java.lang.Object,java.lang.Class) throws EvaluatorException instead.
See also:
jsToJava(java.lang.Object,java.lang.Class)
    public static Object toType(Object valueClass<?> desiredType)
        throws IllegalArgumentException
    {
        try {
            return jsToJava(valuedesiredType);
        } catch (EvaluatorException ex) {
            IllegalArgumentException
                ex2 = new IllegalArgumentException(ex.getMessage());
            Kit.initCause(ex2ex);
            throw ex2;
        }
    }

    
Rethrow the exception wrapping it as the script runtime exception. Unless the exception is instance of EcmaError or EvaluatorException it will be wrapped as WrappedException, a subclass of EvaluatorException. 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.

    {
        while ((e instanceof InvocationTargetException)) {
            e = ((InvocationTargetExceptione).getTargetException();
        }
        // special handling of Error so scripts would not catch them
        if (e instanceof Error) {
            Context cx = getContext();
            if (cx == null ||
                !cx.hasFeature(.))
            {
                throw (Error)e;
            }
        }
        if (e instanceof RhinoException) {
            throw (RhinoException)e;
        }
        throw new WrappedException(e);
    }

    
Tell whether debug information is being generated.

Since:
1.3
    public final boolean isGeneratingDebug()
    {
        return ;
    }

    
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
    public final void setGeneratingDebug(boolean generatingDebug)
    {
        if (onSealedMutation();
         = true;
        if (generatingDebug && getOptimizationLevel() > 0)
            setOptimizationLevel(0);
        this. = generatingDebug;
    }

    
Tell whether source information is being generated.

Since:
1.3
    public final boolean isGeneratingSource()
    {
        return ;
    }

    
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
    public final void setGeneratingSource(boolean generatingSource)
    {
        if (onSealedMutation();
        this. = generatingSource;
    }

    
Get the current optimization level.

The optimization level is expressed as an integer between -1 and 9.

Since:
1.3
    public final int getOptimizationLevel()
    {
        return ;
    }

    
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
    public final void setOptimizationLevel(int optimizationLevel)
    {
        if (onSealedMutation();
        if (optimizationLevel == -2) {
            // To be compatible with Cocoon fork
            optimizationLevel = -1;
        }
        checkOptimizationLevel(optimizationLevel);
        if ( == null)
            optimizationLevel = -1;
        this. = optimizationLevel;
    }
    public static boolean isValidOptimizationLevel(int optimizationLevel)
    {
        return -1 <= optimizationLevel && optimizationLevel <= 9;
    }
    public static void checkOptimizationLevel(int optimizationLevel)
    {
        if (isValidOptimizationLevel(optimizationLevel)) {
            return;
        }
        throw new IllegalArgumentException(
            "Optimization level outside [-1..9]: "+optimizationLevel);
    }

    
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.
    public final int getMaximumInterpreterStackDepth()
    {
        return ;
    }

    
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
    public final void setMaximumInterpreterStackDepth(int max)
    {
        if(onSealedMutation();
        if( != -1) {
            throw new IllegalStateException("Cannot set maximumInterpreterStackDepth when optimizationLevel != -1");
        }
        if(max < 1) {
            throw new IllegalArgumentException("Cannot set maximumInterpreterStackDepth to less than 1");
        }
         = max;
    }

    
Set the security controller for this context.

SecurityController may only be set if it is currently null and SecurityController.hasGlobal() is false. 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(org.mozilla.javascript.SecurityController)
SecurityController.hasGlobal()
    public final void setSecurityController(SecurityController controller)
    {
        if (onSealedMutation();
        if (controller == nullthrow new IllegalArgumentException();
        if ( != null) {
            throw new SecurityException("Can not overwrite existing SecurityController object");
        }
        if (SecurityController.hasGlobal()) {
            throw new SecurityException("Can not overwrite existing global SecurityController object");
        }
         = controller;
    }

    
Set the LiveConnect access filter for this context.

ClassShutter may 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
    public synchronized final void setClassShutter(ClassShutter shutter)
    {
        if (onSealedMutation();
        if (shutter == nullthrow new IllegalArgumentException();
        if () {
            throw new SecurityException("Cannot overwrite existing " +
                                        "ClassShutter object");
        }
         = shutter;
         = true;
    }
    final synchronized ClassShutter getClassShutter()
    {
        return ;
    }
    public interface ClassShutterSetter {
        public void setClassShutter(ClassShutter shutter);
        public ClassShutter getClassShutter();
    }
    public final synchronized ClassShutterSetter getClassShutterSetter() {
        if ()
            return null;
         = true;