[英]Running ECMAScript 5 compliant javascript on Java 7
I would like to run javascript using the embedded javascript engine of Java 7. The code which I am trying to run is ECMAScript 5 compliant, which should not be a problem since the embedded Rhino's version is 1.7 release 3 which supports it. 我想使用Java 7的嵌入式javascript引擎运行javascript。我尝试运行的代码符合ECMAScript 5,这应该不是问题,因为嵌入式Rhino的版本是支持它的1.7版本3 。 Yet, running the following snippet doesn't work:
但是,运行以下代码段不起作用:
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.eval("var char = 'a';");
It fails with the error missing variable name
which indicates that char
is a reserved keyword. 它失败,错误
missing variable name
,表明char
是保留关键字。 However, the char
is no longer reserved in ECMAScript 5, so I am completely confused. 但是,在ECMAScript 5中不再保留
char
,所以我完全感到困惑。 The question is which javascript version is supposed to work with the embedded Rhino in java 7? 问题是哪个javascript版本应该与java 7中的嵌入式Rhino一起使用?
I am using java 1.7.0_80
, the language version reported by the engine is 1.8
and the engine version is 1.7 release 3 PRERELEASE
. 我使用的是java
1.7.0_80
,引擎报告的语言版本是1.8
,引擎版本是1.7 release 3 PRERELEASE
。
As @RealSkeptic pointed out, the embedded script engine of OpenJDK 7 ( Rhino 1.7 r4
) has no problem running the above javascript snippet. 正如@RealSkeptic指出的那样,OpenJDK 7(
Rhino 1.7 r4
)的嵌入式脚本引擎运行上面的javascript片段没有问题。 It seems that Rhino 1.7 r3
can not run it, so running it using Oracle Java 7 needs the external Rhino of 1.7 r4
(or above) which can be downloaded from here . 似乎
Rhino 1.7 r3
无法运行它,因此使用Oracle Java 7运行它需要1.7 r4
(或更高版本)的外部Rhino,可从此处下载。 Just for completeness, the java equivalent of the code in the question based on Rhino's own API looks like this: 为了完整起见,基于Rhino自己的API的问题代码的java等价物如下所示:
import org.mozilla.javascript.Context;
import org.mozilla.javascript.ScriptableObject;
public class Rhino {
public static void main(String[] args) throws Exception {
Context context = Context.enter();
try {
ScriptableObject scope = context.initStandardObjects();
context.evaluateString(scope, "var char = 'a'", "test", 1, null);
} finally {
Context.exit();
}
}
} }
Note that the import declarations are important since the same classes are available bundled in the JDK within a different package: 请注意,导入声明很重要,因为在不同的包中JDK中捆绑了相同的类:
import sun.org.mozilla.javascript.internal.Context;
import sun.org.mozilla.javascript.internal.ScriptableObject;
Importing them yields in using the embedded engine with Rhino's API which will not work. 导入它们会产生使用嵌入式引擎与Rhino的API,这将无法正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.