简体   繁体   中英

Return value from scriptmanager in jdk8

I have been trying the below code

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ScriptCode {
    public static void main(String[] args) throws Exception{
        String code="";
        int y=-1;
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        code="if(a<b){return b;}else{return a;}";
        engine.put("a",10);
        engine.put("b",100);
        y=(int)engine.eval(code);
        System.out.println(y);
    }
}

I am getting an error saying

Caused by: jdk.nashorn.internal.runtime.ParserException: <eval>:1:8 Invalid return statement
if(a<b){return b;}else{return a;}

I am not able to resolve this issue. The issue is that in my usecase, the 'code' variable will have some rules, which will return something. I know how to do it without returning, but I am unable to return some value from the code. How can I do it?

You should declare a function, then execute it, in order to get the results

engine.eval("function max(a,b) { if(a<b){return b;} return a;}");
engine.put("a",10);
engine.put("b",100);
int y = (int)engine.eval("max(a,b)"); // will return function result

or assign the result to a variable, then read it

engine.put("a",10);
engine.put("b",100);
engine.eval("c= a<b? b: a;"); // assign result to a variable
int y = (int) engine.get("c"); // read the value

You had an error, because your return statement was not inside of any function, thus return would not be valid. eval is similar as developer tool console in any browser. You need to declare either a function or an variable.

according to this question you need to write the value you want to return in last row, without return keyword. Your example would look like this (with help variable max )

String code="";
int y=-1;
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
code="if(a<b){" +
        "max = b" +
        "}else{" +
        "max = a" +
        "} " +
        "max";
engine.put("a",10);
engine.put("b",100);
y=(int)engine.eval(code);
System.out.println(y);

You can't return without being inside a function, easy enough to solve; you can define a JavaScript function and invoke it from Java. Like,

ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
String code = "function f(a,b) { if(a<b){return b;}else{return a;}}";
engine.eval(code);
Invocable invocable = (Invocable) engine;
int y = (int) invocable.invokeFunction("f", 10, 100);
System.out.println(y);

Outputs

100

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM