The code below will evaluate a simple JavaScript that produces a “Hello World” message. To evaluate the script, the ScriptEngine
provides us with some overloaded eval()
methods, for instance an eval()
methods that accept the script in string or in Reader
object.
package org.kodejava.script;
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class EvaluatingScript {
public static void main(String[] args) {
// Obtaining the GraalVM Javascript engine
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("graal.js");
try {
// Evaluating a simple script
engine.eval("print('Hello World')");
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
Maven Dependencies
<dependencies>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js</artifactId>
<version>22.3.2</version>
</dependency>
<dependency>
<groupId>org.graalvm.js</groupId>
<artifactId>js-scriptengine</artifactId>
<version>22.3.2</version>
</dependency>
</dependencies>