简体   繁体   English

Java中JavaScript引擎中的未定义对象

[英]Undefined objects in JavaScript engine in Java

Executing the following code in Java7 在Java7中执行以下代码

ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("js");
Bindings b = scriptEngine.createBindings();
b.put("x", true);
scriptEngine.eval("x&y", b);

I get the error 我得到错误

sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "b" is not defined. (<Unknown Source>#1) in <Unknown Source> at line number 1

Is there an option to evaluate to null/false for undefined objects, like in JavaScript? 是否有一个选项可以将未定义的对象的值评估为null / false,例如在JavaScript中?

I know that an option will be to do something like "this.x&this.y" instead of "x&y", but I don't have control over that string (user entered). 我知道一种选择是执行类似“ this.x&this.y”而不是“ x&y”的操作,但是我无法控制该字符串(用户输入)。

I browsed a little bit through the Rhino code and it seems that there's no such option. 我浏览了一下Rhino代码,似乎没有这样的选择。

In the end I will append "this." 最后,我将附加“ this”。 in front of each variable. 在每个变量前面。 This is not by far a desirable solution (I will not even accept my own answer :) ), but for the time being I have no other. 到目前为止,这并不是一个理想的解决方案(我什至不会接受自己的回答:)),但是暂时我没有其他选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM