从Rhino切换到Nashorn [英] Switching from Rhino to Nashorn

查看:795
本文介绍了从Rhino切换到Nashorn的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Java 7项目,该项目大量使用Javascript来编写各种功能的脚本。到现在为止,我使用Rhino作为脚本引擎。我现在想转向Java 8,这也意味着我将取代Nashorn的Rhino。

I have a Java 7 project which makes a lot of use of Javascript for scripting various features. Until now I was using Rhino as script engine. I would now like to move to Java 8, which also means that I will replace Rhino by Nashorn.

Nashorn与Rhino的兼容性如何?我可以将它用作替代品,还是我可以预期我的一些脚本将不再工作并且需要移植到新引擎? Nashorn不支持任何常用的Rhino功能吗?

How compatible is Nashorn to Rhino? Can I use it as a drop-in replacement, or can I expect that some of my scripts will not work anymore and will need to be ported to the new engine? Are there any commonly-used features of Rhino which are not supported by Nashorn?

推荐答案

一个问题是Nashorn不能再通过使用 importPackage(com.organization.project.package);

One problem is that Nashorn can no longer by default import whole Java packages into the global scope by using importPackage(com.organization.project.package);

默认将整个Java包导入全局范围但是,有一个简单的解决方法:通过在脚本中添加此行,您可以启用Rhino的旧行为:

There is, however, a simple workaround: By adding this line to your script, you can enable the old behavior of Rhino:

load("nashorn:mozilla_compat.js");

我遇到的另一个问题是,在java和javascript之间传递数据时,某些类型转换的工作方式不同。例如,将Javascript数组传递给Java时到达的对象不能再转换为 List ,但可以将其强制转换为 Map< ; String,Object> 。作为一种解决方法,您可以使用 Java.to(array,Java.type(java.util.List))将Javascript数组转换为Javascript代码中的Java List。

Another problem I ran into is that certain type-conversions when passing data between java and javascript work differently. For example, the object which arrives when you pass a Javascript array to Java can no longer be cast to List, but it can be cast to a Map<String, Object>. As a workaround you can convert the Javascript array to a Java List in the Javascript code using Java.to(array, Java.type("java.util.List"))

这篇关于从Rhino切换到Nashorn的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆