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