简体   繁体   中英

Returning output value from JavaScript code in Java using Nashorn

I have this short code here

 ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");

        String foo = "print(2);";

        Object s =engine.eval(foo);

        System.out.println(s); // printing null

What i am trying to achieve is that i want the result that engine.eval(foo) will print to save it in a string variable example s value should be 2, how can i realize it in this case that engine.val(foo) is not returning anything.

The root cause of your problem is that Javascript's print() function is not returning a value (in TypeScript it would be function print(): void ). So your code works just fine (you can actually see 2 being printed in stdout) but the return value of print(2); which is void is interpreted as null .

If you invoke a function (or a statement) that returns a value, it will work just fine:

        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");

        String foo = "x = 1+2;";

        Object s = engine.eval(foo);
        System.out.println(s); // printing 3

You can also use variables to handle results:

        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");

        String jsCode = "jsVar = 1+2;";

        engine.eval(jsCode);
        Object javaVar = engine.get("jsVar");

        System.out.println(javaVar); // printing 3

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