|
| 1 | +package com.baeldung.scripting; |
| 2 | + |
| 3 | +import javax.script.Bindings; |
| 4 | +import javax.script.Invocable; |
| 5 | +import javax.script.ScriptEngine; |
| 6 | +import javax.script.ScriptEngineManager; |
| 7 | +import javax.script.ScriptException; |
| 8 | + |
| 9 | +public class Nashorn { |
| 10 | + public static void main(String[] args) throws ScriptException, NoSuchMethodException { |
| 11 | + ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn"); |
| 12 | + |
| 13 | + Object result = engine.eval( |
| 14 | + "var greeting='hello world';" + |
| 15 | + "print(greeting);" + |
| 16 | + "greeting"); |
| 17 | + |
| 18 | + System.out.println(result); |
| 19 | + |
| 20 | + Bindings bindings = engine.createBindings(); |
| 21 | + bindings.put("count", 3); |
| 22 | + bindings.put("name", "baeldung"); |
| 23 | + |
| 24 | + String script = "var greeting='Hello ';" + |
| 25 | + "for(var i=count;i>0;i--) { " + |
| 26 | + "greeting+=name + ' '" + |
| 27 | + "}" + |
| 28 | + "greeting"; |
| 29 | + |
| 30 | + Object bindingsResult = engine.eval(script, bindings); |
| 31 | + System.out.println(bindingsResult); |
| 32 | + |
| 33 | + engine.eval("function composeGreeting(name) {" + |
| 34 | + "return 'Hello ' + name" + |
| 35 | + "}"); |
| 36 | + Invocable invocable = (Invocable) engine; |
| 37 | + |
| 38 | + Object funcResult = invocable.invokeFunction("composeGreeting", "baeldung"); |
| 39 | + System.out.println(funcResult); |
| 40 | + |
| 41 | + Object map = engine.eval("var HashMap = Java.type('java.util.HashMap');" + |
| 42 | + "var map = new HashMap();" + |
| 43 | + "map.put('hello', 'world');" + |
| 44 | + "map"); |
| 45 | + |
| 46 | + System.out.println(map); |
| 47 | + } |
| 48 | +} |
0 commit comments