4

为什么 jsr-223 在是对象的属性时不评估字符串?

只有一个 String 属性的简单类:

public class EvalJSR223Bean {
    public String evalFnt;
}

使用文本和对象的简单评估,当使用对象时,Rhino 不执行评估。但是,如果我将空的 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!!!
}
4

1 回答 1

2

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

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
于 2013-01-17T16:08:18.157 回答