Groovy
is an agile dynamic language for the Java 2 Platform that has many of the features that people like so much in languages like Python, Ruby and Smalltalk, making them available to Java developers using a Java-like syntax.
groovy资源
Official Site:
http://groovy.codehaus.org/JIRA:
http://jira.codehaus.org/secure/BrowseProject.jspa?id=10242Confluence:
http://docs.codehaus.org/display/GROOVY/HomeFounder's blog:
http://radio.weblogs.com/0112098/Project Manager's blog:
http://glaforge.free.fr/weblog/使用IDEA的用户, groovyj非常方便, 不用设定groovy_home, 将jar加入classpath等麻烦事
1. groovy string
def h = 'hello'
def gs = """${h}:
Java,
Python,
Ruby"""
println h[4..0]
println gs
2. groovy beans
class Customer {
@Property Integer id
@Property String name
}
def customer = new Customer(id:6, name:"Water Ye")
println "Hello: ${customer.name}"
//含有只读或只写属性的Bean:
class Foo {
// read only property
private String name
public String getName() { return name }
// read only property with protected setter
@Property Integer amount
protected void setAmount(Integer amount) { this.amount = amount }
// dynamically typed property
def cheese
} 3. Groovy Collections
List:
def list = ['Java', 'Python', 'Ruby']
for (i in list) { println i }
list.each { item | println "${item}" }
Ranges:
def range = 1..10
for (i in range) { println i }
Map:
def map = ["id":6, "firstName":"Water", "lastName":"Ye"]
println map.get("id") + ", " + map["firstName"] + " " + map.lastName
4. Groovy Closures
Closure(闭包): Closures are a powerful way of passing around blocks of executable code. Think of closures as being like anonymous inner classes in Java that have only a single (anonymous) method.
int x, y;
x = 2;
// create closure and assign it to variable C
def c = {numberToSquare -> numberToSquare * numberToSquare }
y = c.call(x) // y == 4 5. GPath
import org.codehaus.groovy.sandbox.util.XmlSlurper
def xmlStr = """
<a>
<b id="b1" name="bn1">
<c id="c1">c1</c>
</b>
<b id="b2" name="bn2">
<c id="c2" >c2</c>
</b>
</a>
"""
def node = new XmlSlurper().parseText(xmlStr)
// 遍历所有b结点
def bs = node.b
for (b in bs)
println "b: id = " + b['@id'] + ", name = " + b['@name']
// 查找c2
def c = node.b.c.find { it['@id'] == 'c2' }
if (c != null)
println c.text()
// 缺点:没有getParent(), 丑陋的解决方法
def b = null
def bs = node.b
for (t in bs) {
def c = t.c.find { it['@id'] == 'c2' }
if (c != null) {
b = t
break
}
} 说明: 江南白衣已实现getParent()
6. groovy builder
import groovy.xml.*
import java.io.*
def writer = new StringWriter()
def builder = new MarkupBuilder(writer)
builder.person() {
name(first:"Water", last:"Ye") {
id("006")
age("25")
gender("male")
email("ychunshui@yahoo.com.cn")
}
}
println writer.toString() 输出结果:
<person>
<name first='Water' last='Ye'>
<id>006</id>
<age>25</age>
<gender>male</gender>
<email>ychunshui@yahoo.com.cn</email>
</name>
</person> 7. Groovlets
// index.groovy
import java.util.Date
import groovy.xml.MarkupBuilder
if (session.counter == null) {
session.counter = 1
}
html = new MarkupBuilder(out)
html.html {
head {
title("Groovy Servlet")
}
body {
p("Hello, ${request.remoteHost}: ${session.counter}! ${new Date()}")
}
}
session.counter = session.counter + 1
<!-- web.xml -->
<servlet>
<servlet-name>Groovy</servlet-name>
<servlet-class>groovy.servlet.GroovyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Groovy</servlet-name>
<url-pattern>*.groovy</url-pattern>
</servlet-mapping> 8. groovy ant task
<taskdef name="groovy"
classname="org.codehaus.groovy.ant.Groovy"
classpathref="my.classpath"/>
<groovy>
println("Hello World")
</groovy> 9. groovy sql
import groovy.sql.Sql
def sql = Sql.newInstance(url, user, password, driver)
def sql = new Sql(dataSource)
def sql = new Sql(connection)
sql.eachRow("select * from person") { row |
println row.id + " " + row.name
}
def goods = sql.dataSet('GOODS')
def material = goods.findAll { it.type == 'M' }
material.each { println "name: ${it.name}" }
sql.execute(sqlStr)
sql.executeUpdate(sqlStr)
sql.call(sqlStr) // 调用过程
sql.rollback()
sql.commit()
sql.close() 注意: 使用groovyj的话, 变量不要和文件名相同, 否则出错