捕获java中的javascript返回值 [英] Capture the javascript return value in java

查看:164
本文介绍了捕获java中的javascript返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过使用Java Sripting API,我可以在Java中执行JavaScript。但是,有人可以解释如何从Java中获取JS的返回值吗?在下面的示例中,我可以使用

By using Java Sripting API, I am able to execute JavaScript within Java. However, can someone please explain how to capture the return value from a JS in Java? In the example below, can I invoke the script2 using

inv.invokeFunction("getValue", "Number", "2);

如何从script2获取返回值?

How can I get the return value from script2?

import javax.script.*;

public class InvokeScriptFunction {
public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");

    // JavaScript code in a String
    String script1 = "function hello(name) {print ('Hello, ' + name);}";
    String script2 = "function getValue(a,b) { if (a==="Number") return 1; 
                     else return b;}";
    // evaluate script
    engine.eval(script1);
    engine.eval(script2);

    Invocable inv = (Invocable) engine;

    inv.invokeFunction("hello", "Scripting!!" );  //This one works.      
 }
}


推荐答案

这是您获得该返回值的方式。

This is how you will get that return value.

String returnValue = (String)inv.invokeFunction("hello", "Scripting!!" );

脚本2相同,只需相应更改通话。

Same for script 2, just change the call accordingly.


Invocable中的invokeFuntion方法返回一个Object。因此,我们必须在使用之前将其类型化为适当的类型。

The invokeFuntion method from Invocable returns an Object. So, we must type-cast it to the appropriate type before using it.

参考

这篇关于捕获java中的javascript返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆