Java 中使用 JavaScript Nashorn 引擎

Nashorn 介绍

Nashorn 是 Java 8 中引入的 JavaScript 引擎,它允许在 Java 应用程序中嵌入和执行 JavaScript 代码。但是在JDK 15 中,Nashorn 已经被移除,取而代之的是新的 JavaScript 引擎,即 GraalVM。如果要继续使用 Nashorn,需要引入相应的依赖。

xml 复制代码
<dependency>
  <groupId>org.openjdk.nashorn</groupId>
  <artifactId>nashorn-core</artifactId>
  <version>15.0</version>
</dependency>

hello world

准备javascript文件,内容如下:

javascript 复制代码
var greeting='hello world';
print(greeting);

在Java 中使用 Nashorn 引擎执行这个文件:

java 复制代码
import org.apache.commons.io.FileUtils;

import javax.script.*;
import java.io.File;

public class TestNashorn {

	public static void main( String args[] ) throws Exception {
		ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");

		String content = FileUtils.readFileToString(new File(TestNashorn.class.getResource("test.js").getFile()), "UTF-8");
		Object result = engine.eval(content);
		System.out.println("result: " + result);
	}
}

传递参数

准备javascript文件,内容如下:

javascript 复制代码
var greeting='hello ' + name;
print(greeting);
greeting

javascript 中使用了一个变量name,最后返回了greeting。

在Java 中使用 Nashorn 引擎执行这个文件,其中使用 Bindings 传递了name参数,然后获取返回值:

java 复制代码
import org.apache.commons.io.FileUtils;

import javax.script.*;
import java.io.File;

public class TestNashorn {

	public static void main( String args[] ) throws Exception {
		ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");
		
		Bindings bind = engine.getBindings(ScriptContext.ENGINE_SCOPE);
		bind.put("name", "kongxx");
		String content = FileUtils.readFileToString(new File(TestNashorn.class.getResource("greeting.js").getFile()), "UTF-8");
		Object result = engine.eval(content);
		System.out.println("result: " + result);
	}
}

调用 Java 类和方法

准备javascript文件,其中调用了 Java 中的 Calendar 类,内容如下:

javascript 复制代码
load('nashorn:mozilla_compat.js');
//importPackage(Packages.java.util);
importClass(java.util.Calendar);

var cal = Calendar.getInstance();
var time = cal.getTimeInMillis();
print(time);
time

在Java 中使用 Nashorn 引擎执行这个文件,然后获取返回值:

java 复制代码
import org.apache.commons.io.FileUtils;

import javax.script.*;
import java.io.File;

public class TestNashorn {

	public static void main( String args[] ) throws Exception {
		ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");
		
		Bindings bind = engine.getBindings(ScriptContext.ENGINE_SCOPE);
		String content = FileUtils.readFileToString(new File(TestNashorn.class.getResource("javaclass.js").getFile()), "UTF-8");
		Object result = engine.eval(content);
		
		System.out.println("result: " + result);
	}
}

调用 JavaScript 函数

准备javascript文件,其中定义了两个函数,内容如下:

javascript 复制代码
var func1 = function() {
    return 'hello world';
}

var func2 = function(name) {
    return 'hello '+ name;
}

在Java 中使用 Nashorn 引擎执行这个文件,其中使用 Invocable 调用函数,并获取返回值:

java 复制代码
import org.apache.commons.io.FileUtils;

import javax.script.*;
import java.io.File;

public class TestNashorn {

	public static void main( String args[] ) throws Exception {
		ScriptEngine engine = new ScriptEngineManager().getEngineByName("Nashorn");

		String content = FileUtils.readFileToString(new File(TestNashorn.class.getResource("function.js").getFile()), "UTF-8");
		engine.eval(content);
		
		Invocable invocable = (Invocable)engine;

		Object result1 = invocable.invokeFunction("func1");
		System.out.println("result: " + result1);

		Object result2 = invocable.invokeFunction("func2", "kongxx");
		System.out.println("result: " + result2);
	}
}
相关推荐
万邦科技Lafite2 小时前
京东按图搜索京东商品(拍立淘) API (.jd.item_search_img)快速抓取数据
开发语言·前端·数据库·python·电商开放平台·京东开放平台
丁浩6662 小时前
Python机器学习---6.集成学习与随机森林
python·随机森林·机器学习
默 语3 小时前
MySQL中的数据去重,该用DISTINCT还是GROUP BY?
java·数据库·mysql·distinct·group by·1024程序员节·数据去重
charlie1145141913 小时前
现代 Python 学习笔记:Statements & Syntax
笔记·python·学习·教程·基础·现代python·python3.13
Never_Satisfied4 小时前
在JavaScript / Node.js / 抖音小游戏中,使用tt.request通信
开发语言·javascript·node.js
oDeviloo4 小时前
新版IntelliJ IDEA个性化设置兼容老版习惯
java·ide·intellij-idea
一只小透明啊啊啊啊4 小时前
Java Web 开发的核心组件:Servlet, JSP,Filter,Listener
java·前端·servlet
spencer_tseng5 小时前
Eclipse Uninstall Software
java·ide·eclipse
嗯、.6 小时前
使用 iText 9 为 PDF 添加文字水印的完整实战
java·pdf·itext
拉不动的猪6 小时前
函数组件和异步组件
前端·javascript·面试