Java中運(yùn)行Groovy,有三種比較常用的類支持
- GroovyShell
- 通常用來運(yùn)行"script片段"或者一些零散的表達(dá)式(Expression)
- GroovyClassLoader
- 如果腳本是一個(gè)完整的文件,特別是有API類型的時(shí)候,比如有類似于JAVA的接口,面向?qū)ο笤O(shè)計(jì)時(shí),通常使用GroovyClassLoader.
- ScriptEngine
- JSR-223應(yīng)該是推薦的一種使用策略.規(guī)范化,而且簡便.
ScriptEngine
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>2.1.6</version>
</dependency>
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-jsr223</artifactId>
<version>2.1.6</version>
</dependency>
public static void evalScript() throws Exception{
ScriptEngineManager factory = new ScriptEngineManager();
//每次生成一個(gè)engine實(shí)例
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文本來自文件,請(qǐng)首先獲取文件內(nèi)容
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);
}
- 實(shí)際案例依疼,Java調(diào)用groovy文件里面的方法荣挨,并傳遞參數(shù)
static void simpleTest() throws IOException, InstantiationException, IllegalAccessException, ResourceException, ScriptException{
String[] roots = new String[] { "src/main/groovy/com/mobile263/billing/groovy/" };
//通過指定的roots來初始化GroovyScriptEngine
GroovyScriptEngine gse = new GroovyScriptEngine(roots);
GroovyObject groovyObject = (GroovyObject) gse.loadScriptByName("TestScript.groovy").newInstance();
String result = (String) groovyObject.invokeMethod("output", "hello");
System.out.println(result);
}
class TestScript {
static String output(def str){
println str;
return "hello"+str;
}
}
傳送門
Groovy入門
Groovy入門
與java的異同
與java的異同
Java嵌入Groovy
Java嵌入Groovy
數(shù)據(jù)庫
import groovy.sql.Sql;
import org.h2.tools.Server;
def db = Sql.newInstance('jdbc:mysql://10.200.1.6:3306/test', 'root', 'aaaaaa', 'com.mysql.jdbc.Driver');
db.execute(''' CREATE TABLE leike(mac varchar(20) NOT NULL PRIMARY KEY)''');
def macs = new File('shroute_inst.csv').readLines()
//重復(fù)的mac地址個(gè)數(shù): 也就是這么多地址更換了平臺(tái).
macs.each{
db.execute('INSERT INTO t1(c) values(?)', [it]);
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者