1. 程式人生 > >JAVA與groovy指令碼的結合使用

JAVA與groovy指令碼的結合使用

java執行groovy shell指令碼

<dependency>

<groupId>org.codehaus.groovy</groupId>

<artifactId>groovy-all</artifactId>

<version>2.4.0-beta-1</version>

</dependency>

新增groovy jar包支援

====================================================

package groovy;

import groovy.lang.Binding;

import groovy.lang.GroovyShell;

public class Java2GroovyShell {

public static void main(String[] args) {

// TODO Auto-generated method stub

Binding binding = new Binding();

binding.setVariable("var", 5);

GroovyShell gs = new GroovyShell(binding);

Object value = gs.evaluate("println 'Hello Groovy !';abc=123;return var*10");//執行groovyshell指令碼

System.out.println(value.equals(50));

System.out.println(binding.getVariable("abc").equals(123));

}

}

====================================================直接執行groovy的指令碼

++++++++++++++++++++++++++++++++++++++++++++++++++++JAVA中動態執行groovy指令碼

通過JAVA來載入如一個groovy指令碼檔案,然後呼叫該指令碼中的方法

package groovy;

import groovy.lang.GroovyClassLoader;

import groovy.lang.GroovyObject;

import java.io.File;

public class Java2GroovyDynamic {

public static void main(String[] args) throws Exception {

// TODO Auto-generated method stub

ClassLoader parent = ClassLoader.getSystemClassLoader();

GroovyClassLoader loader = new GroovyClassLoader(parent);

Class groovyClass = loader.parseClass(new File("C:\\normandy_workspace\\groovy\\src\\groovy\\GroovyDemo.groovy"));

GroovyObject groovyObject = (GroovyObject)groovyClass.newInstance();

Object[] param = {123,321};

int res = (int) groovyObject.invokeMethod("add", param);

System.out.println("res="+res);

}

}

groovy指令碼

package groovy

class GroovyDemo {

static int add(int x,int y) {

return x+y;

}

static main(args) {

int z = add(123,321);

println("x+y="+z);

}

}

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Groovy指令碼引擎

通過設定CLASSPATH來初始化groovy指令碼引擎,可以執行該path下的任何groovy指令碼檔案了

package groovy;

import groovy.lang.Binding;

import groovy.util.GroovyScriptEngine;

public class Java2GroovyEngine {

public static void main(String[] args) throws Exception {

// TODO Auto-generated method stub

String path = "C:\\normandy_workspace\\groovy\\src\\groovy\\";

GroovyScriptEngine gse = new GroovyScriptEngine(path);

Binding binding = new Binding();

binding.setVariable("input", "Groovy");

gse.run("Test.groovy", binding);

System.out.println(binding.getVariable("output"));

}

}

groovy指令碼

package groovy;

output = "Hello ${input}";