我有这个Java访问类的实例在JavaScript程序犀牛:Java的数字不循规蹈矩如Javascript数字
public class ContentProvider {
public Object c(int n) {
switch (n) {
case 1: return 1.1;
case 2: return 2.2;
case 3: return 3.3;
case 4: return "4";
case 5: return new java.util.Date();
}
return null;
}
}
这里面的代码的main():
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
engine.put("ctx", new ContentProvider());
res = engine.eval("ctx.c(1)");
System.out.printf("rhino:> %s (%s)%n"
, res
, res != null ? res.getClass().getName() : null
);
简单的表达ctx.c(1)
打印:
rhino:> 1.1 (java.lang.Double)
现在这里是ctx.c(1) + ctx.c(2)
会发生什么:
rhino:> 1.12.2 (java.lang.String)
最后(ctx.c(1) + ctx.c(2)) * ctx.c(3)
:
rhino:> nan (java.lang.Double)
Rhino是不是执行数算术的字符串连接!下面的程序按预期工作,而不是:
engine.put("a", 1.1);
engine.put("b", 2.2);
engine.put("c", 3.3);
res = engine.eval("(a + b) * c");
输出:
rhino:> 10,89 (java.lang.Double)
哦,我的上帝,有人实际使用的“Java”和“JavaScript的”标签一起* *正确! – immibis
但为什么不尝试'engine.eval(“typeof ctx.c(1)”)'并查看JavaScript认为该类型是什么? – immibis
typeof ctx.c(1)=对象 – lunicon