为什么jsr-223不是在对象的属性时计算字符串?
只有一个String属性的简单类:
public class EvalJSR223Bean {
public String evalFnt;
}
使用文本和对象进行简单评估,当使用对象时,Rhino不执行eval。但是,如果我将空的javascript字符串连接到对象属性,Rhino eval。
public static void main(String[] args) throws ScriptException {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("JavaScript");
engine.eval("function f2() {println('EXECUTED!!!!!')}; function f1(source) { return eval(source); };");
String evalFnt = "(function(){f2();return '0';})();";
engine.put("evalFnt", evalFnt);
engine.eval("f1(evalFnt);"); // f2 is executed.
EvalJSR223Bean bean = new EvalJSR223Bean();
bean.evalFnt = evalFnt;
engine.put("bean1", bean.evalFnt);
engine.eval("f1(bean1.evalFnt);"); // Why does NOT executed f2 ?!!.
engine.put("bean", bean);
engine.eval("f1(bean.evalFnt);"); // Why does NOT executed f2 ?!!.
engine.put("bean", bean);
engine.eval("f1( ''+bean.evalFnt );"); // And if I concatenate a string, f2 is executed!!!
}
答案 0 :(得分:2)
eval
将忽略该字符串:
eval(new String('console.log("foo");'));
所以这可能是Rhino如何将该属性视为“对象”类型的结果。当你put
一个字符串进入引擎时,它必须将它转换为值类型。
此代码:
import javax.script.*;
public class ScriptDemo {
public static class Bar {
public String bar = "bar";
}
public static void main(String[] args) throws ScriptException {
ScriptEngine engine =
new ScriptEngineManager().getEngineByName("JavaScript");
engine.put("foo", "foo");
engine.put("bar", new Bar());
engine.eval("println(typeof foo);");
engine.eval("println(typeof bar.bar);");
engine.eval("println(typeof String(bar.bar));");
engine.eval("println(typeof new String(bar.bar));");
}
}
输出:
string
object
string
object