Fork me on GitHub

Java执行输入的js代码

JDK1.6版添加了新的ScriptEngine类,允许用户直接执行js代码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import java.util.Scanner;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException; /*直接调用js代码*/
public class mc_07241 {
public static void main(String[] args){
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
/*通过脚本名称获取脚本引擎*/
Scanner sc= new Scanner(System.in);
try {
System.out.println(engine.eval(sc.nextLine()));
/*不能调用浏览器中定义的js函数。 错误,会抛出alert等引用不存在的异常*/
} catch (ScriptException e) {
e.printStackTrace();
}
}
}

Your support will encourage me to continue to create!