javaeval
① java如何调用javascript的函数
[java] view plainprint?
<span style="font-size:18px;">package suggestion16;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
import javax.script.Bindings;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class ScriptText {
public static void main(String[] args) throws FileNotFoundException, ScriptException, Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
Bindings bind = engine.createBindings();
bind.put("factor", 2); //这里绑定一个factor的值为2.
engine.setBindings(bind,ScriptContext.ENGINE_SCOPE);
Scanner input = new Scanner(System.in);
while(input.hasNext())
{
int first = input.nextInt();
int sec = input.nextInt();
System.out.println("输入的参数为:"+ first+ " , " + sec);
engine.eval(new FileReader("E:/cal.js"));
if(engine instanceof Invocable)
{
Invocable in = (Invocable)engine;
Double result = (Double)in.invokeFunction("cal",first,sec);
System.out.println("运算结果为:" + result.intValue());
}
}
}
}
</span>
其中的“E:/cal.js”就是我们js文件的保存路径。并且这个主函数可以循环的输入。
我们运行一下这个程序得到的结果如下:
[html] view plainprint?
<span style="font-size:18px;">1
2
输入的参数为:1 , 2
运算结果为:1
</span>
上面也就是 调用了 1 + 2 - 2 = 1 ,所以结果为1
我们将js文件中的function方法改变下,改编为下面的函数:
[javascript] view plainprint?
<span style="font-size:18px;">function cal(var1,var2)
{
return var1+var2*factor;
}</span>