本实例是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>
@After public void tearDown() throws Exception { conn .close(); }
@Test public void testImport() throws Exception { Map
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
throws
Exception; }
GoduDataConnection.java package com.boco.godu.gapi.conn; public class
GoduDataConnection extends AbstractConnection { ......// Other IConnection
Methods public IResult execScript(String name, Map
throws Exception { String[] roots = new String[] {
"e:/MyDoc/Project/GoduScript" }; GroovyScriptEngine gse = new
GroovyScriptEngine(roots); Binding binding = new Binding(); for
(Entry
}
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)。