作者:潘景洪Phant_255 | 来源:互联网 | 2023-08-26 08:01
模拟线上代码(当时服务器上JDK版本为1.7)importjavax.script.ScriptEngine;importjavax.script.ScriptEngineMana
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class Test03 {
public static void main(String[] args) {
// 条件表达式,要求变量a1的值等于变量a2的值、并且变量a3包含"风险"标识
String cOnditionalExpression= "a1==a2&&a3.indexOf("风险")!=-1";
Boolean result = null;
try {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
engine.eval("importPackage(java.util)");
// 给变量赋值
engine.put("a1", 2);
engine.put("a2", 2);
engine.put("a3", "炒股有风险,投资需谨慎。");
Object result1 = engine.eval(conditionalExpression);
if("java.lang.Boolean".equals(result1.getClass().getName())){
result = (Boolean)result1;
}
} catch (ScriptException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("result = " + result);
}
}
在JDK1.7环境下运行代码,其结果是正常的
==================================================================
现在将JDK升级到11,再运行此代码时,就报错了
javax.script.ScriptException: ReferenceError: "importPackage" is not defined in at line number 1
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:564)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:548)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:528)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:524)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:194)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
at study.alibaba.Test03.main(Test03.java:16)
Caused by: :1 ReferenceError: "importPackage" is not defined
at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:56)
at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:318)
at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:290)
at jdk.nashorn.api.scripting.NashornScriptEngine.__noSuchProperty__(NashornScriptEngine.java:274)
at jdk.nashorn.internal.scripts.Script$engine._L35(nashorn:engine/resources/engine.js:37)
at jdk.nashorn.internal.scripts.Script$^eval\_.runScript(:1)
at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:498)
at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:206)
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:378)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:546)
... 5 more
result = null
原来ScriptEngine在后来的JDK版本中,语法进行了调整,已经不支持【importPackage(java.util)】这种写法了
我们将engine.eval("importPackage(java.util)");这行代码删除,再执行就正常了。
result = true