java 呼叫javascript

心鑫發表於2013-08-22
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
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", 1); // 這裡繫結一個factor的值為2.
//		engine.setBindings(bind, ScriptContext.ENGINE_SCOPE);
		int first = 1;
		int sec = 2;
		System.out.println("輸入的引數為:" + first + " , " + sec);
		engine.eval(new FileReader("D:/Project/JavaJS/src/javaus.js"));
		if (engine instanceof Invocable) {
			Invocable in = (Invocable) engine;
			Double result = (Double) in.invokeFunction("add", first, sec);
			System.out.println("運算結果為:" + result.intValue());
		}
	}

}


/**
 * @author Administrator
 */
function add(var1,var2){
return var2+var1;
}


相關文章