java – 为什么Rhino(jsr-223)在它是对象的属性时会对字符串进行求值?

为什么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!!!
}

最佳答案 如果字符串不是“string”类型,则eval忽略该字符串:

eval(new String('console.log("foo");'));

所以这可能是Rhino如何将该属性视为“对象”类型的结果.将字符串放入引擎时,必须将其转换为值类型.

这段代码:

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
点赞