java类javax.script.Invocable的实例源码

CrawlerUtils.java 文件源码 项目:crawler 阅读 16 收藏 0 点赞 0 评论 0
public Object executeJs(String js,@Nullable String funcName,Object... args){
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    try {
        Object res=engine.eval(js);
        if(StringUtils.isNotBlank(funcName)){
            if (engine instanceof Invocable) {
                Invocable invoke = (Invocable) engine;
                res = invoke.invokeFunction(funcName, args);
            }
        }
        return res;
    } catch (Exception e) {
        log.error("",e);
    }
    return null;
}
Test4.java 文件源码 项目:openjdk-jdk10 阅读 18 收藏 0 点赞 0 评论 0
public static void main(String[] args) throws Exception {
    System.out.println("\nTest4\n");
    ScriptEngineManager m = new ScriptEngineManager();
    ScriptEngine e  = Helper.getJsEngine(m);
    if (e == null) {
        System.out.println("Warning: No js engine found; test vacuously passes.");
        return;
    }
    e.eval(new FileReader(
        new File(System.getProperty("test.src", "."), "Test4.js")));
    Invocable inv = (Invocable)e;
    Runnable run1 = (Runnable)inv.getInterface(Runnable.class);
    run1.run();
    // use methods of a specific script object
    Object intfObj = e.get("intfObj");
    Runnable run2 = (Runnable)inv.getInterface(intfObj, Runnable.class);
    run2.run();
}
InvokeScriptFunction.java 文件源码 项目:openjdk-jdk10 阅读 18 收藏 0 点赞 0 评论 0
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "function hello(name) { print('Hello, ' + name); }";
    // evaluate script
    engine.eval(script);

    // javax.script.Invocable is an optional interface.
    // Check whether your script engine implements or not!
    // Note that the JavaScript engine implements Invocable interface.
    final Invocable inv = (Invocable) engine;

    // invoke the global function named "hello"
    inv.invokeFunction("hello", "Scripting!!" );
}
ScopeTest.java 文件源码 项目:openjdk-jdk10 阅读 17 收藏 0 点赞 0 评论 0
@Test
public void invokeFunctionWithCustomScriptContextTest() throws Exception {
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");

    // create an engine and a ScriptContext, but don't set it as default
    final ScriptContext scriptContext = new SimpleScriptContext();

    // Set some value in the context
    scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);

    // Evaluate script with custom context and get back a function
    final String script = "function (c) { return myString.indexOf(c); }";
    final CompiledScript compiledScript = ((Compilable)engine).compile(script);
    final Object func = compiledScript.eval(scriptContext);

    // Invoked function should be able to see context it was evaluated with
    final Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
    assertTrue(((Number)result).intValue() == 1);
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 18 收藏 0 点赞 0 评论 0
@Test
/**
 * Check that calling method on mirror created by another engine results in
 * IllegalArgumentException.
 */
public void invokeMethodMixEnginesTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine1 = m.getEngineByName("nashorn");
    final ScriptEngine engine2 = m.getEngineByName("nashorn");

    try {
        final Object obj = engine1.eval("({ run: function() {} })");
        // pass object from engine1 to engine2 as 'thiz' for invokeMethod
        ((Invocable) engine2).invokeMethod(obj, "run");
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
OQLEngineImpl.java 文件源码 项目:incubator-netbeans 阅读 16 收藏 0 点赞 0 评论 0
public Object unwrapJavaObject(Object object, boolean tryAssociativeArray) {
    if (object == null) return null;
    String className = object.getClass().getName();
    boolean isNativeJS = className.contains(".javascript.")     // NOI18N
                      || className.equals("jdk.nashorn.api.scripting.ScriptObjectMirror"); // NOI18N

    try {
        Object ret = ((Invocable)engine).invokeFunction("unwrapJavaObject", object); // NOI18N
        if (isNativeJS && (ret == null || ret.equals(object)) && tryAssociativeArray) {
            ret = ((Invocable)engine).invokeFunction("unwrapMap", object); // NOI18N
        }
        return ret;
    } catch (Exception ex) {
        LOGGER.log(Level.WARNING, "Error unwrapping JS object", ex); // NOI18N
    }
    return null;
}
OQLEngineImpl.java 文件源码 项目:incubator-netbeans 阅读 17 收藏 0 点赞 0 评论 0
private void init(Snapshot snapshot) throws RuntimeException {
    this.snapshot = snapshot;
    try {
        ScriptEngineManager manager = new ScriptEngineManager();
        engine = manager.getEngineByName("JavaScript"); // NOI18N
        InputStream strm = getInitStream();
        CompiledScript cs = ((Compilable)engine).compile(new InputStreamReader(strm));
        cs.eval();
        Object heap = ((Invocable)engine).invokeFunction("wrapHeapSnapshot", snapshot); // NOI18N
        engine.put("heap", heap); // NOI18N
        engine.put("cancelled", cancelled); // NOI18N
    } catch (Exception ex) {
        LOGGER.log(Level.SEVERE, "Error initializing snapshot", ex); // NOI18N
        throw new RuntimeException(ex);
    }
}
StreamScriptLogic.java 文件源码 项目:Pogamut3 阅读 16 收藏 0 点赞 0 评论 0
/**
 * Constructor which is needed when you have to initialize the
 * environment of the scripting language.
 * <p>
 * Currently used by SPOSHBot.
 */
@Override
public void initializeController(UT2004Bot bot) {
    super.initializeController(bot);
    // first create proper ScriptEngine
    scriptEngineManager = createScriptEngineManager();
    this.engine = createScriptEngine(scriptEngineManager);
    this.invocableEngine = (Invocable) this.engine;
    this.engineBinded();

    // and than load up the script.
    try {
        evalStream(this.getScriptStream());
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new ScriptedAgentException("Unable to evaluate script", ex);
    }
    scriptBinded();
}
ScriptedRegisteredServiceAttributeReleasePolicy.java 文件源码 项目:cas-5.1.0 阅读 25 收藏 0 点赞 0 评论 0
private Map<String, Object> getScriptedAttributesFromFile(final Map<String, Object> attributes) throws Exception {
    final String engineName = getScriptEngineName();
    final ScriptEngine engine = new ScriptEngineManager().getEngineByName(engineName);
    if (engine == null || StringUtils.isBlank(engineName)) {
        LOGGER.warn("Script engine is not available for [{}]", engineName);
        return new HashMap<>();
    }

    final File theScriptFile = ResourceUtils.getResourceFrom(this.scriptFile).getFile();
    if (theScriptFile.exists()) {
        LOGGER.debug("Created object instance from class [{}]", theScriptFile.getCanonicalPath());
        final Object[] args = {attributes, LOGGER};

        LOGGER.debug("Executing  script's run method, with parameters [{}]", args);
        engine.eval(new FileReader(theScriptFile));
        final Invocable invocable = (Invocable) engine;
        final Map<String, Object> personAttributesMap = (Map<String, Object>) invocable.invokeFunction("run", args);

        LOGGER.debug("Final set of attributes determined by the script are [{}]", personAttributesMap);
        return personAttributesMap;
    }
    LOGGER.warn("[{}] script [{}] does not exist, or cannot be loaded", StringUtils.capitalize(engineName), scriptFile);
    return new HashMap<>();
}
NashornKnowledgeBaseInterpreter.java 文件源码 项目:sponge 阅读 16 收藏 0 点赞 0 评论 0
@Override
protected ScriptEngine createScriptEngine() {
    String scripEngineName = SCRIPT_ENGINE_NAME;
    // ScriptEngine result = new ScriptEngineManager().getEngineByName(scripEngineName);
    NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
    ScriptEngine result = factory.getScriptEngine("-scripting");

    Validate.isInstanceOf(Compilable.class, result, "ScriptingEngine %s doesn't implement Compilable", scripEngineName);
    Validate.isInstanceOf(Invocable.class, result, "ScriptingEngine %s doesn't implement Invocable", scripEngineName);

    PROCESSOR_CLASSES.forEach((interfaceClass, scriptClass) -> addImport(result, scriptClass, interfaceClass.getSimpleName()));
    addImport(result, NashornPlugin.class, Plugin.class.getSimpleName());

    getStandardImportClasses().forEach(cls -> addImport(result, cls));

    result.put(KnowledgeBaseConstants.VAR_ENGINE_OPERATIONS, getEngineOperations());

    eval(result, "load(\"classpath:" + INITIAL_SCRIPT + "\");");

    return result;
}
ScriptKotlinKnowledgeBaseInterpreter.java 文件源码 项目:sponge 阅读 17 收藏 0 点赞 0 评论 0
@Override
protected ScriptEngine createScriptEngine() {
    String scripEngineName = SCRIPT_ENGINE_NAME;
    ScriptEngine result = new ScriptEngineManager().getEngineByName(scripEngineName);

    Validate.isInstanceOf(Compilable.class, result, "ScriptingEngine %s doesn't implement Compilable", scripEngineName);
    Validate.isInstanceOf(Invocable.class, result, "ScriptingEngine %s doesn't implement Invocable", scripEngineName);

    KotlinConstants.PROCESSOR_CLASSES
            .forEach((interfaceClass, scriptClass) -> addImport(result, scriptClass, interfaceClass.getSimpleName()));
    addImport(result, KPlugin.class, Plugin.class.getSimpleName());

    // TODO The line below performs very slow in Kotlin
    eval(result, getStandardImportClasses().stream().map(cls -> "import " + cls.getName()).collect(Collectors.joining("\n")));

    setVariable(result, KnowledgeBaseConstants.VAR_ENGINE_OPERATIONS, getEngineOperations());

    return result;
}
GoogleTranslator.java 文件源码 项目:GoogleTranslation 阅读 17 收藏 0 点赞 0 评论 0
private String tk(String val) throws Exception {
    String script = "function tk(a) {"
            + "var TKK = ((function() {var a = 561666268;var b = 1526272306;return 406398 + '.' + (a + b); })());\n"
            + "function b(a, b) { for (var d = 0; d < b.length - 2; d += 3) { var c = b.charAt(d + 2), c = 'a' <= c ? c.charCodeAt(0) - 87 : Number(c), c = '+' == b.charAt(d + 1) ? a >>> c : a << c; a = '+' == b.charAt(d) ? a + c & 4294967295 : a ^ c } return a }\n"
            + "for (var e = TKK.split('.'), h = Number(e[0]) || 0, g = [], d = 0, f = 0; f < a.length; f++) {"
            + "var c = a.charCodeAt(f);"
            + "128 > c ? g[d++] = c : (2048 > c ? g[d++] = c >> 6 | 192 : (55296 == (c & 64512) && f + 1 < a.length && 56320 == (a.charCodeAt(f + 1) & 64512) ? (c = 65536 + ((c & 1023) << 10) + (a.charCodeAt(++f) & 1023), g[d++] = c >> 18 | 240, g[d++] = c >> 12 & 63 | 128) : g[d++] = c >> 12 | 224, g[d++] = c >> 6 & 63 | 128), g[d++] = c & 63 | 128)"
            + "}"
            + "a = h;"
            + "for (d = 0; d < g.length; d++) a += g[d], a = b(a, '+-a^+6');"
            + "a = b(a, '+-3^+b+-f');"
            + "a ^= Number(e[1]) || 0;"
            + "0 > a && (a = (a & 2147483647) + 2147483648);"
            + "a %= 1E6;"
            + "return a.toString() + '.' + (a ^ h)\n"
            + "}";

    engine.eval(script);
    Invocable inv = (Invocable) engine;
    return (String) inv.invokeFunction("tk", val);
}
ScriptRouter.java 文件源码 项目:saluki 阅读 21 收藏 0 点赞 0 评论 0
@Override
public boolean match(List<GrpcURL> providerUrls) {
  String rule = super.getRule();
  try {
    engine.eval(super.getRule());
    Invocable invocable = (Invocable) engine;
    GrpcURL refUrl = super.getRefUrl();
    Object obj = invocable.invokeFunction("route", refUrl, providerUrls);
    if (obj instanceof Boolean) {
      return (Boolean) obj;
    } else {
      return true;
    }
  } catch (ScriptException | NoSuchMethodException e) {
    log.error("route error , rule has been ignored. rule: " + rule + ", url: " + providerUrls, e);
    return true;
  }
}
TestMain.java 文件源码 项目:slardar 阅读 29 收藏 0 点赞 0 评论 0
public static void main(String[] args) {
        ScriptEngineManager engineManager = new ScriptEngineManager();
        ScriptEngine engine = engineManager.getEngineByName("javascript");
        try {
//            UserVO user = new UserVO();
//            user.setId(1000);
//            user.setUsername("xingtianyu");
//            Map<String,Object> usermap = new HashMap<>();
//            usermap.put("id",user.getId());
//            usermap.put("username",user.getUsername());
            JSContext context = new JSContext();
            engine.put(JSContext.CONTEXT,context.getCtx());
            engine.eval(new FileReader("/home/code4j/IDEAWorkspace/myutils/myutils-slardar/src/main/resources/mapper/usermapper.js"));
            Invocable func = (Invocable)engine;
//            Map<String,Object> resultMap = (Map<String, Object>) func.invokeFunction("findUserByCondition",usermap);
//            Map<String,Object> paramMap = (Map<String, Object>) resultMap.get("param");
//            System.out.println(resultMap.get("sql"));
//            System.out.println(paramMap.get("1"));
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
Test8.java 文件源码 项目:openjdk-jdk10 阅读 22 收藏 0 点赞 0 评论 0
public static void main(String[] args) throws Exception {
    System.out.println("\nTest8\n");
    ScriptEngineManager m = new ScriptEngineManager();
    ScriptEngine e  = Helper.getJsEngine(m);
    if (e == null) {
        System.out.println("Warning: No js engine found; test vacuously passes.");
        return;
    }
    e.eval(new FileReader(
        new File(System.getProperty("test.src", "."), "Test8.js")));
    Invocable inv = (Invocable)e;
    inv.invokeFunction("main", "Mustang");
    // use method of a specific script object
    Object scriptObj = e.get("scriptObj");
    inv.invokeMethod(scriptObj, "main", "Mustang");
}
RunnableImplObject.java 文件源码 项目:openjdk-jdk10 阅读 16 收藏 0 点赞 0 评论 0
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "var obj = new Object(); obj.run = function() { print('run method called'); }";

    // evaluate script
    engine.eval(script);

    // get script object on which we want to implement the interface with
    final Object obj = engine.get("obj");

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script methods of object 'obj'
    final Runnable r = inv.getInterface(obj, Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
InvokeScriptMethod.java 文件源码 项目:openjdk-jdk10 阅读 16 收藏 0 点赞 0 评论 0
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String. This code defines a script object 'obj'
    // with one method called 'hello'.
    final String script = "var obj = new Object(); obj.hello = function(name) { print('Hello, ' + name); }";
    // evaluate script
    engine.eval(script);

    // javax.script.Invocable is an optional interface.
    // Check whether your script engine implements or not!
    // Note that the JavaScript engine implements Invocable interface.
    final Invocable inv = (Invocable) engine;

    // get script object on which we want to call the method
    final Object obj = engine.get("obj");

    // invoke the method named "hello" on the script object "obj"
    inv.invokeMethod(obj, "hello", "Script Method !!" );
}
RunnableImpl.java 文件源码 项目:openjdk-jdk10 阅读 14 收藏 0 点赞 0 评论 0
public static void main(final String[] args) throws Exception {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");

    // JavaScript code in a String
    final String script = "function run() { print('run called'); }";

    // evaluate script
    engine.eval(script);

    final Invocable inv = (Invocable) engine;

    // get Runnable interface object from engine. This interface methods
    // are implemented by script functions with the matching name.
    final Runnable r = inv.getInterface(Runnable.class);

    // start a new thread that runs the script implemented
    // runnable interface
    final Thread th = new Thread(r);
    th.start();
    th.join();
}
ScopeTest.java 文件源码 项目:openjdk-jdk10 阅读 24 收藏 0 点赞 0 评论 0
@Test
public void invokeFunctionInGlobalScopeTest() throws Exception {
     final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
     final ScriptContext ctxt = engine.getContext();

     // define a function called "func"
     engine.eval("func = function() { return 42 }");

     // move ENGINE_SCOPE Bindings to GLOBAL_SCOPE
     ctxt.setBindings(ctxt.getBindings(ScriptContext.ENGINE_SCOPE), ScriptContext.GLOBAL_SCOPE);

     // create a new Bindings and set as ENGINE_SCOPE
     ctxt.setBindings(engine.createBindings(), ScriptContext.ENGINE_SCOPE);

     // define new function that calls "func" now in GLOBAL_SCOPE
     engine.eval("newfunc = function() { return func() }");

     // call "newfunc" and check the return value
     final Object value = ((Invocable)engine).invokeFunction("newfunc");
     assertTrue(((Number)value).intValue() == 42);
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 20 收藏 0 点赞 0 评论 0
@Test
/**
 * Check that we can call invokeMethod on an object that we got by
 * evaluating script with different Context set.
 */
public void invokeMethodDifferentContextTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        // define an object with method on it
        final Object obj = e.eval("({ hello: function() { return 'Hello World!'; } })");

        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        e.setContext(ctxt);

        // invoke 'func' on obj - but with current script context changed
        final Object res = ((Invocable) e).invokeMethod(obj, "hello");
        assertEquals(res, "Hello World!");
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 22 收藏 0 点赞 0 评论 0
@Test
/**
 * Check that invokeMethod throws NPE on null method name.
 */
public void invokeMethodNullNameTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        final Object obj = e.eval("({})");
        ((Invocable) e).invokeMethod(obj, null);
        fail("should have thrown NPE");
    } catch (final Exception exp) {
        if (!(exp instanceof NullPointerException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 17 收藏 0 点赞 0 评论 0
@Test
/**
 * Check that invokeMethod throws NoSuchMethodException on missing method.
 */
public void invokeMethodMissingTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        final Object obj = e.eval("({})");
        ((Invocable) e).invokeMethod(obj, "nonExistentMethod");
        fail("should have thrown NoSuchMethodException");
    } catch (final Exception exp) {
        if (!(exp instanceof NoSuchMethodException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 23 收藏 0 点赞 0 评论 0
@Test
/**
 * Check that calling method on non-script object 'thiz' results in
 * IllegalArgumentException.
 */
public void invokeMethodNonScriptObjectThizTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable) e).invokeMethod(new Object(), "toString");
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 22 收藏 0 点赞 0 评论 0
@Test
/**
 * Check that calling method on null 'thiz' results in
 * IllegalArgumentException.
 */
public void invokeMethodNullThizTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable) e).invokeMethod(null, "toString");
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 18 收藏 0 点赞 0 评论 0
@Test
/**
 * Try passing non-interface Class object for interface implementation.
 */
public void getNonInterfaceGetInterfaceTest() {
    final ScriptEngineManager manager = new ScriptEngineManager();
    final ScriptEngine engine = manager.getEngineByName("nashorn");
    try {
        log(Objects.toString(((Invocable) engine).getInterface(Object.class)));
        fail("Should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            fail("IllegalArgumentException expected, got " + exp);
        }
    }
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 17 收藏 0 点赞 0 评论 0
@Test
/**
 * Check that we can get interface out of a script object even after
 * switching to use different ScriptContext.
 */
public void getInterfaceDifferentContext() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");
    try {
        final Object obj = e.eval("({ run: function() { } })");

        // change script context
        final ScriptContext ctxt = new SimpleScriptContext();
        ctxt.setBindings(e.createBindings(), ScriptContext.ENGINE_SCOPE);
        e.setContext(ctxt);

        final Runnable r = ((Invocable) e).getInterface(obj, Runnable.class);
        r.run();
    } catch (final Exception exp) {
        exp.printStackTrace();
        fail(exp.getMessage());
    }
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 16 收藏 0 点赞 0 评论 0
@Test
/**
 * Check that getInterface on non-script object 'thiz' results in
 * IllegalArgumentException.
 */
public void getInterfaceNonScriptObjectThizTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable) e).getInterface(new Object(), Runnable.class);
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 27 收藏 0 点赞 0 评论 0
@Test
/**
 * Check that getInterface on null 'thiz' results in
 * IllegalArgumentException.
 */
public void getInterfaceNullThizTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable) e).getInterface(null, Runnable.class);
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 22 收藏 0 点赞 0 评论 0
@Test
/**
 * Check that calling getInterface on mirror created by another engine
 * results in IllegalArgumentException.
 */
public void getInterfaceMixEnginesTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine engine1 = m.getEngineByName("nashorn");
    final ScriptEngine engine2 = m.getEngineByName("nashorn");

    try {
        final Object obj = engine1.eval("({ run: function() {} })");
        // pass object from engine1 to engine2 as 'thiz' for getInterface
        ((Invocable) engine2).getInterface(obj, Runnable.class);
        fail("should have thrown IllegalArgumentException");
    } catch (final Exception exp) {
        if (!(exp instanceof IllegalArgumentException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}
InvocableTest.java 文件源码 项目:openjdk-jdk10 阅读 26 收藏 0 点赞 0 评论 0
@Test
/**
 * check that null function name results in NPE.
 */
public void invokeFunctionNullNameTest() {
    final ScriptEngineManager m = new ScriptEngineManager();
    final ScriptEngine e = m.getEngineByName("nashorn");

    try {
        ((Invocable)e).invokeFunction(null);
        fail("should have thrown NPE");
    } catch (final Exception exp) {
        if (!(exp instanceof NullPointerException)) {
            exp.printStackTrace();
            fail(exp.getMessage());
        }
    }
}


问题


面经


文章

微信
公众号

扫码关注公众号