admin管理员组

文章数量:1327694

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);

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.      
 }
}

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);

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.      
 }
}
Share Improve this question asked Oct 28, 2013 at 3:30 user2300206user2300206 733 silver badges7 bronze badges 1
  • if i write above code in servlet then can we say that JavaScript is running at serverside? – Prashant Shilimkar Commented Oct 28, 2013 at 4:10
Add a ment  | 

1 Answer 1

Reset to default 6

This is how you will get that return value.

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

Same for script 2, just change the call accordingly.

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

Reference

本文标签: Capture the javascript return value in javaStack Overflow