Reputation: 943
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
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