在使用ScriptEngineManager遇到的坑。
直接上代码
1 public static void main(String[] args) { 2 // TODO Auto-generated method stub 3 String exp = "3==3 & 43>=20 & 4<5"; 4 ScriptEngine jse = new ScriptEngineManager() 5 .getEngineByName("JavaScript"); 6 7 try { 8 Object value =jse.eval(exp); 9 if(value instanceof Integer) { 10 if((int)value>0) { 11 System.out.println("yes"); 12 }else{ 13 System.out.println("no"); 14 } 15 } 16 17 18 } catch (ScriptException e) { 19 // TODO Auto-generated catch block 20 e.printStackTrace(); 21 } 22 }
在windows环境下执行,正常可以打印yes。但是把程序放到linux上,发现不打印任何东西。
经过排查问题出现在:
Object value =jse.eval(exp); 在linux中返回值为Double类型。
1 public static void main(String[] args) { 2 // TODO Auto-generated method stub 3 String exp = "3==3 & 43>=20 & 4<5"; 4 ScriptEngine jse = new ScriptEngineManager() 5 .getEngineByName("JavaScript"); 6 7 try { 8 Object value =jse.eval(exp); 9 if(value instanceof Double) { 10 if((Double)value>0) { 11 System.out.println("yes"); 12 }else{ 13 System.out.println("no"); 14 } 15 } 16 17 18 } catch (ScriptException e) { 19 // TODO Auto-generated catch block 20 e.printStackTrace(); 21 } 22 }
修改为以上代码后,在linux上执行正常。