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);
	}
}
相关推荐
CaracalTiger24 分钟前
什么是Clawdbot?Clawdbot下载、安装、配置教程(最新版Moltbot)
python·编辑器·aigc·idea·ai编程·intellij idea·agi
WJX_KOI5 小时前
Open Notebook 一个开源的结合AI的记笔记软件
python
0思必得06 小时前
[Web自动化] 反爬虫
前端·爬虫·python·selenium·自动化
徐徐同学6 小时前
cpolar为IT-Tools 解锁公网访问,远程开发再也不卡壳
java·开发语言·分布式
2301_822382766 小时前
Python上下文管理器(with语句)的原理与实践
jvm·数据库·python
喵手6 小时前
Python爬虫实战:从零搭建字体库爬虫 - requests+lxml 实战采集字体网字体信息数据(附 CSV 导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·csv导出·采集字体库数据·字体库字体信息采集
2401_892000527 小时前
Flutter for OpenHarmony 猫咪管家App实战 - 添加提醒实现
前端·javascript·flutter
Yolanda947 小时前
【项目经验】vue h5移动端禁止缩放
前端·javascript·vue.js
Mr.朱鹏7 小时前
Nginx路由转发案例实战
java·运维·spring boot·nginx·spring·intellij-idea·jetty
2301_790300967 小时前
Python深度学习入门:TensorFlow 2.0/Keras实战
jvm·数据库·python