⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 context.java

📁 java中比较著名的js引擎当属mozilla开源的rhino
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
    /**     * Create an array with a specified initial length.     * <p>     * @param scope the scope to create the object in     * @param length the initial length (JavaScript arrays may have     *               additional properties added dynamically).     * @return the new array object     */    public final Scriptable newArray(Scriptable scope, int length)    {        NativeArray result = new NativeArray(length);        ScriptRuntime.setObjectProtoAndParent(result, scope);        return result;    }    /**     * Create an array with a set of initial elements.     *     * @param scope the scope to create the object in.     * @param 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[].     * @return the new array object.     */    public final Scriptable newArray(Scriptable scope, Object[] elements)    {        if (elements.getClass().getComponentType() != ScriptRuntime.ObjectClass)            throw new IllegalArgumentException();        NativeArray result = new NativeArray(elements);        ScriptRuntime.setObjectProtoAndParent(result, scope);        return result;    }    /**     * Get the elements of a JavaScript array.     * <p>     * 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.     * @param object the JavaScript array or array-like object     * @return 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.     * <p>     * See ECMA 9.2.     *     * @param value a JavaScript value     * @return 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.     * <p>     * Returns a Java double for the JavaScript Number.     * <p>     * See ECMA 9.3.     *     * @param value a JavaScript value     * @return 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.     * <p>     * See ECMA 9.8.     * <p>     * @param value a JavaScript value     * @return 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.     * <p>     * Note that a scope must be provided to look up the constructors     * for Number, Boolean, and String.     * <p>     * See ECMA 9.9.     * <p>     * 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.     *     * @param value any Java object     * @param scope global scope containing constructors for Number,     *              Boolean, and String     * @return new JavaScript object     */    public static Scriptable toObject(Object value, Scriptable scope)    {        return ScriptRuntime.toObject(scope, value);    }    /**     * @deprecated     * @see #toObject(Object, Scriptable)     */    public static Scriptable toObject(Object value, Scriptable scope,                                      Class staticType)    {        return ScriptRuntime.toObject(scope, value);    }    /**     * Convenient method to convert java value to its closest representation     * in JavaScript.     * <p>     * 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.     * <p>     * Note that for Number instances during any arithmetic operation in     * JavaScript the engine will always use the result of     * <tt>Number.doubleValue()</tt> resulting in a precision loss if     * the number can not fit into double.     * <p>     * If value is an instance of Character, it will be converted to string of     * length 1 and its JavaScript type will be string.     * <p>     * The rest of values will be wrapped as LiveConnect objects     * by calling {@link WrapFactory#wrap(Context cx, Scriptable scope,     * Object obj, Class staticType)} as in:     * <pre>     *    Context cx = Context.getCurrentContext();     *    return cx.getWrapFactory().wrap(cx, scope, value, null);     * </pre>     *     * @param value any Java object     * @param scope top scope object     * @return value suitable to pass to any API that takes JavaScript values.     */    public static Object javaToJS(Object value, Scriptable 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(cx, scope, value, null);        }    }    /**     * 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.     * @param value the JavaScript value to convert     * @param desiredType the Java type to convert to. Primitive Java     *        types are represented using the TYPE fields in the corresponding     *        wrapper class in java.lang.     * @return the converted value     * @throws EvaluatorException if the conversion cannot be performed     */    public static Object jsToJava(Object value, Class desiredType)        throws EvaluatorException    {        return NativeJavaObject.coerceTypeImpl(desiredType, value);    }    /**     * @deprecated     * @see #jsToJava(Object, Class)     * @throws IllegalArgumentException if the conversion cannot be performed.     *         Note that {@link #jsToJava(Object, Class)} throws     *         {@link EvaluatorException} instead.     */    public static Object toType(Object value, Class desiredType)        throws IllegalArgumentException    {        try {            return jsToJava(value, desiredType);        } catch (EvaluatorException ex) {            IllegalArgumentException                ex2 = new IllegalArgumentException(ex.getMessage());            Kit.initCause(ex2, ex);            throw ex2;        }    }    /**     * Rethrow the exception wrapping it as the script runtime exception.     * Unless the exception is instance of {@link EcmaError} or     * {@link EvaluatorException} it will be wrapped as     * {@link WrappedException}, a subclass of {@link EvaluatorException}.     * The resulting exception object always contains     * source name and line number of script that triggered exception.     * <p>     * This method always throws an exception, its return value is provided     * only for convenience to allow a usage like:     * <pre>     * throw Context.throwAsScriptRuntimeEx(ex);     * </pre>     * to indicate that code after the method is unreachable.     * @throws EvaluatorException     * @throws EcmaError     */    public static RuntimeException throwAsScriptRuntimeEx(Throwable e)    {        while ((e instanceof InvocationTargetException)) {            e = ((InvocationTargetException) e).getTargetException();        }        // special handling of Error so scripts would not catch them        if (e instanceof Error) {            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 generatingDebug;    }    /**     * Specify whether or not debug information should be generated.     * <p>     * Setting the generation of debug information on will set the     * optimization level to zero.     * @since 1.3     */    public final void setGeneratingDebug(boolean generatingDebug)    {        if (sealed) onSealedMutation();        generatingDebugChanged = true;        if (generatingDebug && getOptimizationLevel() > 0)            setOptimizationLevel(0);        this.generatingDebug = generatingDebug;    }    /**     * Tell whether source information is being generated.     * @since 1.3     */    public final boolean isGeneratingSource()    {        return generatingSource;    }    /**     * Specify whether or not source information should be generated.     * <p>     * 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 (sealed) onSealedMutation();        this.generatingSource = generatingSource;    }    /**     * Get the current optimization level.     * <p>     * The optimization level is expressed as an integer between -1 and     * 9.     * @since 1.3     *     */    public final int getOptimizationLevel()    {        return optimizationLevel;    }        /**     * Set the current optimization level.     * <p>     * 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.     * @param optimizationLevel an integer indicating the level of     *        optimization to perform     * @since 1.3     *     */    public final void setOptimizationLevel(int optimizationLevel)    {        if (sealed) onSealedMutation();        if (optimizationLevel == -2) {            // To be compatible with Cocoon fork            optimizationLevel = -1;        }        checkOptimizationLevel(optimizationLevel);        if (codegenClass == null)            optimizationLevel = -1;        this.optimizationLevel = 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 StackOv

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -