java groovy_Java和groovy相互调用

这篇博客展示了如何在Java中调用Groovy脚本并执行Groovy类的方法,以及Groovy如何调用Java方法。通过GroovyClassLoader和GroovyShell,实现了Java-Groovy的交互。示例代码详细解释了过程。
摘要由CSDN通过智能技术生成

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");

}

}

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2012-12-18 23:54

浏览 6807

评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值