使用Java调用JS


import junit.framework.TestCase; import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.swing.JButton;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors; public class CallJs extends TestCase {
public void testConsoleLog() throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
//此处会抛出异常,Java的script引擎并不包含console对象
engine.eval("console.log('hello world')");
} public void testConsoleLog2() throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
engine.put("console", System.out);
//此处会抛出异常,Java的script引擎并不包含console对象
engine.eval("console.println('hello world')");
} public void testUseJsFunction() throws ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
engine.eval("function add(x,y){return x+y}");
Object value = engine.eval("add(3,7)");
System.out.println(value.getClass() + " " + value);
} /**
* 注意,这个内部类必须是public否则js编译器看不见
*/
public class SubWrapper {
public int sub(int x, int y) {
return x - y;
}
} public void testUseJsFile() throws IOException, ScriptException {
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
InputStream cin = getClass().getResourceAsStream("/calljs.js");
InputStreamReader reader = new InputStreamReader(cin);
engine.put("subWrapper", new SubWrapper());
engine.eval(reader);
engine.put("console", System.out);
System.out.println(engine.eval("add(3,4)"));
System.out.println(engine.eval("sub(5,6)"));
} public void testUpdateJavaObject() throws ScriptException {
JButton button = new JButton();
ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
engine.put("button", button);
engine.eval("button.text='hello world'");
System.out.println(button.getText());
} public void testlistAllScriptEngine() {
//列出全部脚本引擎
new ScriptEngineManager().getEngineFactories().forEach(fac -> {
System.out.println("name " + fac.getEngineName()
+ "\nlanguage " + fac.getLanguageName()
+ "\nversion " + fac.getEngineVersion()
+ "\nlanguageVersion " + fac.getLanguageVersion()
+ "\nextensions " + fac.getExtensions().stream().collect(Collectors.joining(","))
+ "\nmimetypes " + fac.getMimeTypes().stream().collect(Collectors.joining(","))
+ "\n"
);
});
} }

js

function add(x, y) {
return x + y
} function sub(x,y){
return subWrapper.sub(x,y)
}
上一篇:this的相关介绍与用法


下一篇:JQ 常见demo