jdk6 对 javascript 的支持

原文链接: http://jnotnull.iteye.com/blog/262384

package com.lch.js;

import java.io.File;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;



public class HelloWorld {

	/**
	 * @param args
	 * @throws ScriptException 
	 * @throws NoSuchMethodException 
	 */
	public static void main(String[] args) throws Exception {
		ScriptEngineManager factory = new ScriptEngineManager();
		ScriptEngine engine = factory.getEngineByName("javascript");
		//engine.eval("print('hello')");
		//testScriptVariables(engine);//演示如何暴露JAVA对象为脚本语言的全局对象
		//testInvokeScriptMethod(engine);//演示JAVA中如何调用脚本语言
		//testScriptInterface(engine);//演示脚本语言如何实现JAVA接口
		testUsingJDKClasses(engine);//演示脚本如何使用JDK平台下的类
		
	}
	
	public static void testScriptVariables(ScriptEngine engine) throws ScriptException{
		File file = new File("test.txt");
		engine.put("f", file);
		engine.eval("println('otal space: ' + f.getTotalSpace())");
	}
	
	public static void testInvokeScriptMethod(ScriptEngine engine) throws ScriptException, NoSuchMethodException{
		String script = "function hello(name) {return 'hello ' + name;}";
		engine.eval(script);
		Invocable inv = (Invocable)engine;
		String res = (String)inv.invokeFunction("hello", "Scripting");
		System.out.println("res : " + res);
	}
	
	public static void testScriptInterface(ScriptEngine engine) throws ScriptException{
		String script = "var obj = new Object(); obj.run = function(){ println('run method called');}";
		engine.eval(script);
		Object obj = engine.get("obj");
		Invocable inv = (Invocable)engine;
		Runnable r = inv.getInterface(obj, Runnable.class);
		Thread th = new Thread(r);
		th.start();
	}

	public static void testUsingJDKClasses(ScriptEngine engine) throws ScriptException, NoSuchMethodException{
		String js = "function doSwing(t){var f = new Packages.javax.swing.JFrame(t); f.setSize(400, 300); f.setVisible(true);}";
		engine.eval(js);
		Invocable inv = (Invocable)engine;
		inv.invokeFunction("doSwing", "Scripting Swing");
	}
}

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