概述
java interface
- package groovy;
- public interface IFoo {
- public Object run(Object foo, Object bar);
- }
groovy implements
- package groovy;
- class Foo implements IFoo {
- def x
- public Object run(Object foo, Object bar) {
- println 'Hello World!'
- x = 123
- println foo * 10
- println bar
- return 'success'
- }
- }
java call groovy
- package groovy;
- import groovy.lang.GroovyClassLoader;
- import groovy.lang.GroovyObject;
- import java.io.File;
- public class InvokeGroovy {
- public static void main(String[] args) {
- ClassLoader cl = new InvokeGroovy().getClass().getClassLoader();
- GroovyClassLoader groovyCl = new GroovyClassLoader(cl);
- try {
- @SuppressWarnings("rawtypes")
- Class groovyClass = groovyCl.parseClass(new File(InvokeGroovy.class.getResource("/groovy/Foo.groovy").toURI()));
- IFoo foo = (IFoo) groovyClass.newInstance();
- System.out.println(foo.run(new Integer(2), "More parameter..."));
- System.out.println("=============================");
- GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
- System.out.println(groovyObject.invokeMethod("run", new Object[]{new Integer(2),"More parameter..."}));
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
java execute groovy script
- package groovy;
- import groovy.lang.Binding;
- import groovy.lang.GroovyShell;
- import javax.script.ScriptEngine;
- import javax.script.ScriptEngineManager;
- import javax.script.ScriptException;
- public class TestEval {
- public Object doit() {
- ScriptEngineManager factory = new ScriptEngineManager(TestEval.class.getClassLoader());
- ScriptEngine scriptEngine = factory.getEngineByName("groovy");//或者"Groovy" groovy版本要1.6以上的
- try {
- scriptEngine.put("test", "hello world!");
- scriptEngine.put("outer", this);
- scriptEngine.eval("println test; outer.java_out()");
- } catch (ScriptException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- Binding bb = new Binding();
- bb.setVariable("test", "hello world!");
- bb.setProperty("outer", this);
- GroovyShell gs = new GroovyShell(bb);
- return gs.evaluate("println test; outer.java_out()");
- }
- /**
- * @param args
- */
- public static void main(String[] args) {
- TestEval te = new TestEval();
- te.doit();
- }
- public void java_out(){
- System.out.println("out from java");
- }
- }
最后
以上就是沉默日记本为你收集整理的Java和groovy相互调用的全部内容,希望文章能够帮你解决Java和groovy相互调用所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复