Search code examples
javascriptjavaeval

Java JSObject.eval() is not working, is there any import needed?


I have tried a few different ways to JavaScript functions, control structures, etc, in java, among them, JSObject.eval():

public class Interpreter{
    public static void eval (String input) {
        JSObject.eval(input);
    }
    public static void main (String[ ] args) {
        Interpreter Program = new Interpreter();
        Program.eval("console.log('hello');");
    }
}

Outputs:

_Interpreter.java:92: error: cannot find symbol
        JSObject.eval(input);
        ^
  symbol:   variable JSObject
  location: class Interpreter
1 error_

Solution

  • You can use the ScriptEngine API to evaluate JS scripts:

    //with the following imports:
    import javax.script.ScriptEngine;
    import javax.script.ScriptEngineManager;
    import javax.script.ScriptException;
    
    
    public static void main (String[ ] args) {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("js");
            try {
                Object result = engine.eval("var a = 4, b = 5; a * b");
                System.out.println(result);
            }catch (ScriptException e){
                e.printStackTrace();
            }
        }