Zizou
Zizou

Reputation: 943

String expression interpolation support in java scripting engines

I'm using groovy/nashorn as java engine but not able to interpolate Strings.

jdk.nashorn.api.scripting.NashornScriptEngine  scriptEngine =(NashornScriptEngine) factory.getEngineByName("nashorn");
ScriptContext context = scriptEngine.getContext();
Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("x","Guest");
engine.eval("Hello, ${x}",context);

But I'm getting javax.script.ScriptException. Is Sttring interpolation supported? Thanks

Upvotes: 2

Views: 310

Answers (1)

Szymon Stepniak
Szymon Stepniak

Reputation: 42174

There are two things worth mentioning:

  • if you want to evaluate Groovy script, you might need to use

    new ScriptEngineManager().getEngineByExtension("groovy");
    
  • the script passed to engine.eval() method has to be a valid Groovy code. The script code you passed to the eval method is not a valid Groovy code - you expect to interpolate a string, but you didn't put it inside the double quotes.

Consider the following example:

ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("groovy");
ScriptContext context = engine.getContext();
Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("x","Guest");
Object result = engine.eval("\"Hello, ${x}\"", context);

System.out.println(result);

The output:

Hello, Guest

Alternatively, you may pass a Groovy script that prints the interpolated script. In this case the code may look like this:

ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("groovy");
ScriptContext context = engine.getContext();
Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE);
bindings.put("x","Guest");
engine.eval("println \"Hello, ${x}\"", context);

It produces the same output, but does not assign Hello, Guest to a variable.

Upvotes: 0

Related Questions