Why doesn't Rhino (jsr-223) evaluate a string if it is an attribute of an object?

Why doesn't jsr-223 evaluate a string when it is an attribute of an object?

A simple class with only one String attribute:

public class EvalJSR223Bean { public String evalFnt; } 

A simple evaluation using text and an object, and when an object is used, Rhino does not perform an eval. But if I concatenate an empty javascript string into an 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!!! } 
+4
source share
1 answer

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

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

Thus, this is probably a consequence of how Rhino views the property as an “object” type. When you put enter a string into the engine, it should convert it to a 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 
+2
source

All Articles