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);
	}
}
相关推荐
锐湃2 分钟前
手写agp8自定义插件,用ASM实现路由跳转
java·服务器·前端
馬致远8 分钟前
Flask - MySQL 蓝图风格小项目搭建
python·mysql·flask
啃火龙果的兔子11 分钟前
Pygame开发游戏流程详解
python·游戏·pygame
千寻girling14 分钟前
面试官: “ 请你讲一下 package.json 文件 ? ”
前端·javascript·面试
如果你好16 分钟前
解决深拷贝循环引用痛点:一篇看懂 WeakMap 实现方案
前端·javascript
weixin_4784333218 分钟前
iluwatar 设计模式
java·开发语言·设计模式
花卷HJ18 分钟前
Android 多媒体文件工具类封装(MediaFileUtils)
android·java
BoBoZz1919 分钟前
AmbientSpheres 调整材质的环境光系数来控制3D物体的着色效果
python·vtk·图形渲染·图形处理
han_19 分钟前
前端性能优化之性能指标篇
前端·javascript·性能优化
爱生活的苏苏20 分钟前
修改默认滚动条样式
开发语言·javascript·ecmascript