ScriptEngine使⽤java调⽤js代码JDK1.6版添加了新的ScriptEngine类,允许⽤户直接执⾏js代码。
不能调⽤浏览器中定义的js函数,会抛出异常提⽰ReferenceError: “alert” is not defined。
package com.sinaapp.manjushri;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException; /** * 直接调⽤js代码 */
public class ScriptEngineTest {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = EngineByName("javascript");
try {
engine.eval("var a=3; var b=4;print (a+b);");
// 不能调⽤浏览器中定义的js函数
// engine.eval("alert(\"js alert\");");
// 错误,会抛出alert引⽤不存在的异常
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
输出结果:7
在调⽤(key);时,如果key没有定义,则返回null
package com.sinaapp.manjushri;
import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ScriptEngineTest2 {
public static void main(String[] args) {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = EngineByName("javascript");
engine.put("a", 4); engine.put("b", 3);
Bindings bindings = Bindings(ScriptContext.ENGINE_SCOPE);
try {
// 只能为Double,使⽤Float和Integer会抛出异常
Double result = (Double) engine.eval("a+b");
System.out.println("result = " + result);
engine.eval("c=a+b");
Double c = (("c");
System.out.println("c = " + c);
} catch (ScriptException e) {
e.printStackTrace();
}
}
}
输出:
result = 7.0
c = 7.0
js⽂件中的merge函数将两个参数a,b相加,并返回c。
// expression.js
function merge(a, b) {
c = a * b;
return c;
}
如何下载javascript在Java代码中读取js⽂件,并参数两个参数,然后回去返回值
package com.sinaapp.manjushri;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
/** * Java调⽤并执⾏js⽂件,传递参数,并活动返回值 * * @author manjushri */ public class ScriptEngineTest {
public static void main(String[] args) throws Exception {
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = EngineByName("javascript");
String jsFileName = "expression.js";
// 读取js⽂件
FileReader reader = new FileReader(jsFileName);
// 执⾏指定脚本
engine.eval(reader);
if(engine instanceof Invocable) {
Invocable invoke = (Invocable)engine;
// 调⽤merge⽅法,并传⼊两个参数
// c = merge(2, 3);
Double c = (Double)invoke.invokeFunction("merge", 2, 3);
System.out.println("c = " + c);
}
reader.close();
}
}
输出结果:
c = 5.0
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论