Java动态调用Groovy

 

package com.neeao.groovy;

import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyShell;
import groovy.util.GroovyScriptEngine;

public class helloGroovy {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		long time = System.currentTimeMillis();
		fun1();
		fun2();
		fun3();
		System.out.print(System.currentTimeMillis() - time);
		System.out.println(" ms");
	}

	private static void fun3() {
		try {
			GroovyScriptEngine engine = new GroovyScriptEngine("");
			Binding binding = new Binding();
			binding.setVariable("language", "Groovy");
			Object value = engine.run("SimpleScript.groovy", binding);
			assert value.equals("The End");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static void fun2() {
		Binding binding = new Binding();
		binding.setVariable("x", 10);
		binding.setVariable("language", "Groovy");
		GroovyShell shell = new GroovyShell(binding);
		Object value = shell.evaluate("println \"Welcome to $language\"; y = x * 2; z = x * 3; println x ");
		assert value.equals(10);
		assert binding.getVariable("y").equals(20);
		assert binding.getVariable("z").equals(30);
	}

	private static void fun1() {
		GroovyClassLoader loader = new GroovyClassLoader();
		try {
			String scriptText = "class Foo {\n"
					+ "  int add(int x, int y) { x + y }}";
			Class<?> newClazz = loader.parseClass(scriptText);
			Object obj = newClazz.newInstance();
			Object i = obj.getClass().getMethod("add", int.class, int.class)
					.invoke(obj, 23, 3);
			System.out.println(i);
		} catch (Exception e) {

		}
	}

}

参考:

http://zjx158.iteye.com/blog/770763

http://tglnn.iteye.com/blog/376978

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注