Groovy在Java中的应用,做几个小例子以备查
package com.boco.efficiency.groovy;
import groovy.lang.Binding;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.GroovyShell;
import groovy.text.SimpleTemplateEngine;
import groovy.text.Template;
import groovy.util.GroovyScriptEngine;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import org.codehaus.groovy.control.CompilationFailedException; public class groovyUsage {
private static final Logger logger = Logger.getLogger(groovyUsage.class);
/*
* UseClassLoader usage example
* Use groovy UseClassLoader to parse/compile a groovy file and run it
* */
public void UseClassLoader() throws Exception {
ClassLoader parent = getClass().getClassLoader();
GroovyClassLoader loader = new GroovyClassLoader(parent);
Class groovyClass = loader.parseClass(new File("D:\\StudyCode\\checkGroovy\\src\\main\\java\\com\\boco\\common\\HelloWorld.groovy"));
GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
Object[] args = {};
groovyObject.invokeMethod("sayHello", args);
} /*
* GroovyShell usage example
* Use groovy shell to calculate dynamically
注意其中的groovyShell.evalucate会比较好用
* */
public void UseGroovyShell() {
Binding binding = new Binding();
binding.setVariable("foo", new Integer(30));
GroovyShell shell = new GroovyShell(binding);
Object value = shell.evaluate("println 'Hello World! I\\'m in shell'; x = 123; return foo * 10");
logger.info("result: " + value);
assert value.equals(new Integer(20));
} /*
* GroovyScriptEngine usage example
* GroovyScriptEngine是实际场景中应用最多的,其构造参数中需要加入urls指明groovy应用路径
* */
public void useGroovyScriptEngine() throws Exception {
String[] roots = new String[] { "/StudyCode/checkGroovy/src/main/java/com/boco/common/" };
GroovyScriptEngine gse = new GroovyScriptEngine(roots);
Binding binding = new Binding();
binding.setVariable("input", "world");
gse.run("hello.groovy", binding);
logger.info(binding.getVariable("output"));
} /*
* Use groovy.Text.Template to gen new String
这在动态生成某些文本文件或script时会有大用处^^
* */
public void useGroovyTextTemplate() throws Exception {
File file=new File("D:\\StudyCode\\checkGroovy\\src\\main\\java\\com\\boco\\common\\template.tmpl");
Template tmpl =null;
try {
tmpl = new SimpleTemplateEngine().createTemplate(file);
} catch (CompilationFailedException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} Map binding = new HashMap();
binding.put("id", "101");
binding.put("name", "101");
binding.put("salary", "50000");
String xml = tmpl.make(binding).toString();
logger.info(xml);
}
}
配置文件信息
D:\StudyCode\checkGroovy\src\main\java\com\haha\common>cat hello.groovy
output = "Hello, ${input}!"
D:\StudyCode\checkGroovy\src\main\java\com\haha\common>cat HelloWorld.groovy
class HelloWorld {
public void sayHello() {
System.out.println("hello world from HelloWorld.groovy");
}
}
D:\StudyCode\checkGroovy\src\main\java\com\haha\common>cat check.groovy
import com.haha.common.alarmObj;
public class check {
public void localHandle(alarmObj src,alarmObj dest) {
long newfp3=src.getFp0()+src.getFp1()+src.getFp2();
System.out.println("call in groovy: " + newfp3);
}
}
D:\StudyCode\checkGroovy\src\main\java\com\haha\common>cat template.tmpl
<WholeMsg MsgMark='1231' Priority='' FieldNum=''>
<person>
<id>${id}</id>
<name>${name}</name>
<salary>${salary}</salary>
</person>
</WholeMsg>
调用各用例
package com.boco.efficiency.groovy; import java.io.File;
public class groovyCheck {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
groovyUsage groovyExample = new groovyUsage();
groovyExample.UseGroovyShell();
groovyExample.UseClassLoader();
groovyExample.useGroovyScriptEngine();
groovyExample.useGroovyTextTemplate();
}
}
最终输出
Hello World! I'm in shell
[2013-11-05 17:03:47,432] INFO [com.boco.efficiency.groovy.groovyUsage] - [result: 300]
hello world from HelloWorld.groovy
[2013-11-05 17:03:47,488] INFO [com.boco.efficiency.groovy.groovyUsage] - [Hello, world!]
[2013-11-05 17:03:47,506] INFO [com.boco.efficiency.groovy.groovyUsage] - [<WholeMsg MsgMark='1231' Priority='' FieldNum=''>
<person>
<id>101</id>
<name>101</name>
<salary>50000</salary>
</person>
</WholeMsg>]
参考文档