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>
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024