java调用js代码和js调用java类和方法示例
Author:[email protected] Date:
NodeJS带来的原生异步并发与事件驱动编程模型得到认可,但是因为其单线程缘故,不能简单方便地从事密集计算,而java优势是多线程并发,Java 8又引入了Lambda表达式,使得Java多线程并发在处理高CPU负载的计算上既强大又方便,那么我们是否对于Javascript中那些密集计算,比如对集合中的map操作,或聚合操作reduce使用Java实现呢?
答案是可以的,利用Java8的Javascript引擎 Nashorn。比如我们可以将Js如下的lambda在JVM中实现:
import com.pagoda.model.UserInfo; import javax.script.*; import java.text.DecimalFormat; public class Main { public static void main(String[] args){ try { ScriptEngineManager sem=new ScriptEngineManager(); ScriptEngine engine=sem.getEngineByName("nashorn"); String js; js = "var names = [\"john\", \"jerry\", \"bob\"]\n"; js += "var a = names[0];\n"; js += "print(a)"; engine.eval(js); String js2="var BigDecimal = Java.type('java.math.BigDecimal'); \n" + "\n" + "function calculate(amount, percentage) { \n" + " var result = new BigDecimal(amount).multiply( \n" + " new BigDecimal(percentage)).divide( \n" + " new BigDecimal(\"100\"), 2, BigDecimal.ROUND_HALF_EVEN); \n" + " return result.toPlainString(); \n" + "}\n" + "var result = calculate(568000000000000000023,13.9); \n" + "print(result);"; engine.eval(js2); } catch (ScriptException e) { e.printStackTrace(); } } }
详细可见文章:Java 8: Compiling Lambda Expressions in The New Nashorn JS Engine
转载本站文章《java调用js代码和js调用java类和方法示例》,
请注明出处:https://www.zhoulujun.cn/html/java/javaBase/7772.html