문제

Why does not jsr-223 evaluate string when is a attribute of a object?

Simple class with only one String attribute:

public class EvalJSR223Bean {
    public String evalFnt;
}

Simple evaluation using text and object, and when is used the object, Rhino does not execute eval. But if I concatenate empty javascript string to object property, 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!!!
}
도움이 되었습니까?

해결책

eval ignores the string if the string is not of type "string":

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

So this is likely a consequence of how Rhino treats the property as being of type "object". When you put a string into the engine, it must convert it to the value type.

This code:

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));");
  }
}

Output:

string
object
string
object
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top