The editor of Downcodes will show you the various methods of Java calling JavaScript! Interoperability between Java and JavaScript is increasingly important, and this article will take an in-depth look at four mainstream methods: using ScriptEngineManager, Nashorn JavaScript engine, Duktape, and GraalVM. Each of these methods has its own advantages and disadvantages and is suitable for different scenarios, helping developers to flexibly use the powerful functions of JavaScript in Java applications to improve development efficiency and application performance. The article will help you quickly master these technologies through clear code examples and detailed explanations, and comes with FAQs to help you gain a deeper understanding of the interaction between Java and JavaScript.

Java code can call JavaScript scripts in a variety of ways, including using ScriptEngineManager, Nashorn JavaScript engine, Duktape, and GraalVM. These technologies make it possible to execute JavaScript code in the Java virtual machine, thereby increasing the flexibility and functionality of JavaScript in Java applications.
For example, using ScriptEngineManager is a common way for Java to call JavaScript scripts because it is a standard method built into Java. In addition, with the launch of Oracle's new high-performance GraalVM, running JavaScript scripts through GraalVM has become more efficient.
The Java platform provides the ScriptEngineManager class, which is part of the javax.script package in Java SE 6 and above, which is specifically designed to provide integration with scripting languages. ScriptEngineManager allows Java code to interact with scripting languages, thereby taking advantage of scripting languages' advantages, such as rapid development and dynamic typing.
To use ScriptEngineManager, you just need to create an instance of it and obtain the JavaScript execution environment through it. Here is a simple example of how to use ScriptEngineManager:
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class JavaScriptFromJava {
public static void mAIn(String[] args) {
// Create ScriptEngineManager object
ScriptEngineManager manager = new ScriptEngineManager();
// Get the ScriptEngine of JavaScript
ScriptEngine engine = manager.getEngineByName(JavaScript);
try {
//Execute JavaScript code
engine.eval(print('Hello, World!'));
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
Nashorn, introduced since Java SE 8, is a high-performance JavaScript engine that allows running JavaScript on the JVM, providing better performance and compatibility with the ECMAScript 5.1 specification.
Similar to ScriptEngineManager, you need to use this class to obtain an instance of the Nashorn engine and execute JavaScript code.
import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
public class NashornExample {
public static void main(String[] args) {
// Create ScriptEngineManager
ScriptEngineManager manager = new ScriptEngineManager();
// Get Nashorn's ScriptEngine
ScriptEngine engine = manager.getEngineByName(nashorn);
try {
//Execute JavaScript script
engine.eval(print('Hello, Nashorn!'));
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
Duktape is an embedded JavaScript engine that is lightweight, easy to integrate, and can provide a JavaScript execution environment in various systems. Duktape is suitable for situations where you need to run JavaScript in resource-constrained environments.
Because Duktape is a JavaScript engine written in C, it usually needs to be integrated with Java applications through JNI (Java Native Interface). Corresponding JNI code needs to be written to bridge the Java code and the Duktape engine.
// Assume there is already a JNI interface
public class DuktapeExample {
//JNI method declaration
public native String executeScript(String script);
static {
//Load the library containing Native method implementation
System.loadLibrary(duktape);
}
public static void main(String[] args) {
DuktapeExample example = new DuktapeExample();
// Call Duktape to execute JavaScript through JNI
String result = example.executeScript(var msg = 'Hello, Duktape!'; msg;);
System.out.println(result);
}
}
GraalVM is a brand new virtual machine that can execute multiple languages, including Java and JavaScript. The purpose of GraalVM is to provide a single runtime to execute all programming languages, which is characterized by high performance and multi-language coexistence.
In GraalVM, you can use the Context class to create a runtime environment for executing JavaScript.
import org.graalvm.polyglot.*;
public class GraalVMExample {
public static void main(String[] args) {
// Use GraalVM's Context to run JavaScript code
try (Context context = Context.create()) {
// Run JavaScript code
Value result = context.eval(js, print('Hello, GraalVM!'););
}
}
}
Through the above methods, Java can call JavaScript scripts and utilize the dynamic programming characteristics of JavaScript in different scenarios. Whether through ScriptEngineManager, Nashorn, Duktape or GraalVM, Java and JavaScript interoperability provides developers with powerful tools to create flexible and feature-rich applications.
1. How to call JavaScript script in Java code?
Calling JavaScript scripts in Java can be achieved by using Java's ScriptEngine interface. First, you need to create a ScriptEngine instance and then load the JavaScript script into the instance. Next, you can use the eval() method of the ScriptEngine instance to execute JavaScript code. For example:
//Create ScriptEngine instance ScriptEngineManager manager = new ScriptEngineManager();ScriptEngine engine = manager.getEngineByName(JavaScript);try { //Load JavaScript script engine.eval(function sayHello() { return 'Hello, World!'; }); // Call JavaScript function Object result = engine.eval(sayHello()); // Output result System.out.println(result.toString());} catch (ScriptException e) { e.printStackTrace();}2. How to pass Java objects to JavaScript scripts?
If you want to access a Java object in a JavaScript script, you can bind the Java object to a global variable in the ScriptEngine instance. In this way, you can use the variable in a JavaScript script to call the Java object's methods and access its properties. For example:
//Create a ScriptEngine instance ScriptEngineManager manager = new ScriptEngineManager();ScriptEngine engine = manager.getEngineByName(JavaScript);try { //Bind the Java object to the global variable in ScriptEngine engine.put(myObject, new MyObject()); // Use this variable in JavaScript script engine.eval(myObject.sayHello(););} catch (ScriptException e) { e.printStackTrace();}// Define a Java object public class MyObject { public void sayHello() { System.out.println(Hello from Java!); }}3. How to get the return value of JavaScript script in Java?
To obtain the return value of a JavaScript script, you can use the eval() method of the ScriptEngine instance to execute the script and store the return value in a variable. For example:
//Create a ScriptEngine instance ScriptEngineManager manager = new ScriptEngineManager();ScriptEngine engine = manager.getEngineByName(JavaScript);try { //Execute the JavaScript script and get the return value Object result = engine.eval(function sayHello() { return 'Hello, World!'; } sayHello();); // Output result System.out.println(result.toString());} catch (ScriptException e) { e.printStackTrace();}In the above code, the return value of the JavaScript script is the string Hello, World!. By storing the result of executing the script in the result variable, we can print out this return value.
I hope this article can help you better understand how Java calls JavaScript. For more Java-related knowledge, please continue to follow the editor of Downcodes!