Java和Groovy脚本互相调用实例

本实例是GODU动态脚本的一个技术简化版,演示了java调groovy,groovy又调java的运行过程。 测试用例: package com.boco.godu.integration;

import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import com.boco.godu.gapi.ConnManager; import com.boco.godu.gapi.Constants; import com.boco.godu.gapi.IConnection; import com.boco.godu.gapi.IResult;

public class SimpleExpScriptTest { private static final Logger logger = Logger . getLogger (SimpleExpScriptTest. class ); private IConnection conn ;

@Before public void setUp() throws Exception { conn = ConnManager. getDataConn ( "10.0.2.47" , 1234, "< aa ><7001>" , "goduapp" , Constants. TYPE_DATA_CMD_SYNC , 5); }

@After public void tearDown() throws Exception { conn .close(); }

@Test public void testImport() throws Exception { Map params = new HashMap(); params.put( "cmd1" , "ls" ); params.put( "id" , 3); ,>,>

IResult result =  conn .execScript( "ImportEx" , params);

} }

Java代码: IConnection.java package com.boco.godu.gapi; public interface IConnection { ......// other method definition public IResult execScript (String name, Map params)
throws Exception; }
,>

GoduDataConnection.java package com.boco.godu.gapi.conn; public class GoduDataConnection extends AbstractConnection { ......// Other IConnection Methods public IResult execScript(String name, Map params)
throws Exception { String[] roots = new String[] { "e:/MyDoc/Project/GoduScript" }; GroovyScriptEngine gse = new GroovyScriptEngine(roots); Binding binding = new Binding(); for (Entry item : params.entrySet()) { binding.setVariable(item.getKey(), item.getValue()); } GapiIosessionUtils giu = new GapiIosessionUtils(); binding.setVariable( "giu" , giu ); gse.run(name, binding); System. out .println(binding.getVariable( "result" )); // 运行结果是这里输出“11”,即3*2+5。 return null ; } ,>
,>

}

GapiIosessionUtils.java

package com.boco.godu.gapi.util; public class GapiIosessionUtils { ......// other method public int testM( int x, int y) { return x * 2 + y; } }

groovy代码:

e:\MyDoc\Project\GoduScript\ImportEx

def send(cmd){

def result = giu.testM(cmd,5);

return result;

}

result = send(id)

运行过程 测试用例 ->GoduDataConnection.java -> groovy代码 -> GapiIosessionUtils.java;

总结 binding的setVariable中定义的变量(如giu是com.boco.godu.gapi.util.GapiIosessionUtils对象,id是int型数据)在groovy脚本里直接使用,可以出现在脚本的任何地方,且无需声明类型,无需使用import导入定义该变量的类(例如对于giu来说,如果在java代码中,需要import com.boco.godu.gapi.util.GapiIosessionUtils)。

Java和Groovy脚本互相调用实例,布布扣,bubuko.com

Java和Groovy脚本互相调用实例

上一篇:将vim打造成Java IDE


下一篇:Python代码规范