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>