3

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.      
 }
}
1
  • if i write above code in servlet then can we say that JavaScript is running at serverside? Commented Oct 28, 2013 at 4:10

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.