Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture the javascript return value in java

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.      
 }
}
like image 474
user2300206 Avatar asked Dec 03 '25 14:12

user2300206


1 Answers

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

like image 136
Hanky Panky Avatar answered Dec 06 '25 02:12

Hanky Panky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!