JAVA结合JAVASCRIPT的应用实例

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 AScript {
	public static void main(String[] arg) {
		ScriptEngineManager factory = new ScriptEngineManager();
		/**
		 * 浏览可用的脚本引擎
		 */
		// for (ScriptEngineFactory available : factory.getEngineFactories()) {
		// System.out.println(available.getEngineName());
		// }
		ScriptEngine engine = factory.getEngineByName("JavaScript");

		HelloWorld hello = new HelloWorld();
		
		
		/**
		 * 把java对象加入脚本中,作为脚本变量
		 */
		engine.put("script_hello", hello);
		// try {
		// engine.eval("script_hello.sayHello()");
		// } catch (ScriptException e) {
		// // TODO Auto-generated catch block
		// e.printStackTrace();
		// }
		try {
			engine.eval(new FileReader("HelloWorld.js"));
			
			/**
			 * 在java中调用脚本函数
			 */
			Invocable inv = (Invocable) engine;
			inv.invokeFunction("Person", "Tony");
			System.out.println("====================脚本实现java接口,java中调用实现=============================");
			MaxMin maxMin = inv.getInterface(MaxMin.class);
			System.out.println(maxMin.max(2, 1));
			System.out.println(maxMin.min(2, 1));
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ScriptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

HelloWorld.js

script_hello.sayHello()
var life={};
for(life.age=1;life.age<=3;life.age++)
{
	switch(life.age)
	{
		case 1:
		life.body="我出生了";
		life.say = function(){print(this.body+'\n')};
		break;
		case 2:
		life.body="我长大了";
		life.brother="小弟弟变大了";
		life.say = function(){print(this.body+this.brother+'\n')};
		break;
		case 3:
		life.body="我老了";
		life.brother="儿子出来了";
		life.say = function(){print(this.body+this.brother+'\n')};
		break;
	}
	life.say();
}
function Person(name)
{
 print(name);
}

function min(first,second)
{
 return (first < second) ?first:second;
}

function max(first,second)
{
 return (first > second) ?first:second;
}




java接口MaxMin

public interface MaxMin {
	public int max(int a, int b);
	public int min(int a, int b);
	}

你可能感兴趣的:(JavaScript,java,脚本)