标签:
在java中调用Groovy类,需要增加Groovy运行时到java的classpath中。
pom.xml
<dependency> <groupId>org.codehaus.groovy</groupId> <artifactId>groovy-all</artifactId> <version>2.4.5</version> </dependency> |
创建一个包:de.vogella.groovy.java
创建一个Groovy类。
package de.vogella.groovy.java
import groovy.transform.ToString
@ToString() class Person { String firstName String lastName int age def address }
|
创建一个java类
package de.vogella.groovy.java;
public class Main { public static void main(String[] args) { Person p = new Person(); p.setFirstName("zuoys"); p.setLastName("遥远2"); System.out.println(p.getFirstName() + " " + p.getLastName()); System.out.println(p.toString()); }
} |
输出:
zuoys 遥远2 de.vogella.groovy.java.Person(zuoys, 遥远2, 0, null) |
http://www.tuicool.com/articles/baQRVf
JSR223方式
package de.vogella.groovy.java;
import java.util.Date;
import javax.script.Bindings; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager;
public class ExecuteGroovyViaJSR223 {
public static void main(String[] args) { ScriptEngineManager factory = new ScriptEngineManager(); // 每次生成一个engine实例 ScriptEngine engine = factory.getEngineByName("groovy"); System.out.println(engine.toString()); assert engine != null; // javax.script.Bindings Bindings binding = engine.createBindings(); binding.put("date", new Date()); // 如果script文本来自文件,请首先获取文件内容 try { engine.eval("def getTime(){return date.getTime();}", binding); engine.eval("def sayHello(name,age){return ‘Hello,I am ‘ + name + ‘,age‘ + age;}"); Long time = (Long) ((Invocable) engine).invokeFunction("getTime", null); System.out.println("执行结果:"+time); String message = (String) ((Invocable) engine).invokeFunction("sayHello", "zhangsan", new Integer(12)); System.out.println("执行结果:"+message); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); }
}
}
|
输出
org.codehaus.groovy.jsr223.GroovyScriptEngineImpl@38af3868 执行结果:1469518145323 执行结果:Hello,I am zhangsan,age12
|
标签:
原文地址:http://www.cnblogs.com/yaoyuan2/p/5719227.html