前言:
不同开发语言之间具有通用性,更具有协作调用的可能。有时候对于一些场景会有调用js的需求,因此下面展示了一个java利用自身JDK调用js函数的demo,供感兴趣的朋友参考。
js函数文件 expression.js
function merge(a, b) { c = a * b; return c; } function isPrime (num) { if (num <= 1) { print("Please enter a positive integer >= 2.") return false } var prime = true var sqrRoot = Math.round(Math.sqrt(num)) for (var n = 2; prime & n <= sqrRoot; ++n) { prime = (num % n != 0) } return prime }
java调用代码:
package com.yeezhao.common.js; import java.io.FileReader; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; /** * JAVA 调用 js脚本 * @author Administrator -> junhong * @since 2016年12月14日 上午11:20:00 */ public class ScriptEngineTest { public static void main(String[] args) throws Exception { ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("javascript"); String jsFileName = "expression.js"; // 读取js文件 String path = ScriptEngineTest.class.getClassLoader().getResource("").getPath(); System.out.println("path=" + path); FileReader reader = new FileReader(path + jsFileName); // 执行指定脚本 engine.eval(reader); if (engine instanceof Invocable) { Invocable invoke = (Invocable) engine; // 调用merge方法,并传入两个参数 // c = merge(2, 3); Double c = (Double) invoke.invokeFunction("merge", 2, 3); System.out.println("c = " + c); // ok = isPrime(5); Integer[] nums = { 1, 2, 3, 5, 12, 112, 100, 4351561 }; for (Integer num : nums) { System.out.println(num + " --> " + invoke.invokeFunction("isPrime", num)); } //hellp invoke.invokeFunction("hello1", "John"); } reader.close(); } }
输出Output:
path=/D:/Eclipse/workspace/yz-test-20161207/target/classes/ c = 6.0 Please enter a positive integer >= 2.1 --> false 2 --> true 3 --> true 5 --> true 12 --> false 112 --> false 100 --> false 4351561 --> true before hello2 ----> hello2 John after hello2