Chinaunix首页 | 论坛 | 博客
  • 博客访问: 29958733
  • 博文数量: 708
  • 博客积分: 12163
  • 博客等级: 上将
  • 技术积分: 8240
  • 用 户 组: 普通用户
  • 注册时间: 2007-12-04 20:59
文章分类

全部博文(708)

分类: Java

2009-06-05 15:05:49

11、语句

1)分号

l         Groovy使用类似Java的语法,但是语句的分号是可选的

l         如果每行一个语句,就可以省略分号;如果一行上有多个语句,就要用分号来分隔

x = [1, 2, 3]
println x
y = 5; x = y + 7
println x
assert x == 12

l         一个语句可以跨越多行,对于方法的参数列表或复杂的表达式,可能会这样做

x = [1, 2, 3,
       4, 5, 6]
println(
       x
)
if (x != null && 
       x.size() > 5) {
       println("Works!")
} else {
       assert false: "should never happen ${x}"
}

2)方法调用

l         方法调用的语法和Java类似,支持静态和实例方法

class Foo {
       calculatePrice() {
              1.23
       }
       static void main(args) {
              foo = new Foo()
              p = foo.calculatePrice()
              assert p > 0
              println "Found price: " + p
       }
}

l         注意,return关键字在方法的最后是可选的;同样,返回类型也是可选(缺省是Object

l         Groovy中方法的调用可以省略括号,只要有参数,并且没有歧义

3)传递命名参数

l         在调用方法时,可以传递命名参数,参数的名字和值用分号分隔(象Map语法),参数名是唯一标识字符串

bean = new Expando(name:"James", location:"London", id:123)
println "Hey " + bean.name
assert bean.id == 123

l         当前这种方法传递只实现具有Map的方法调用或JavaBean构造

4)传递闭包给方法

请参考《Groovy快速入门

5)动态方法分派

l         如果变量没有使用类型强制,动态方法分派被使用,这经常被指为动态类型,而Java缺省使用静态类型

l         可以在代码中混合使用动态和静态类型

dynamicObject = "hello world".replaceAll("world", "Gromit")
dynamicObject += "!"
assert dynamicObject == "hello Gromit!"
 
String staticObject = "hello there"
staticObject += "!"
assert staticObject == "hello there!"

6)属性

l         通过“.属性名”访问属性

bean = new Expando(name:"James", location:"London", id:123)
name = bean.name
println("Hey ${name}")
bean.location = "Vegas"
println bean.name + " is now in " + bean.location
assert bean.location == "Vegas"

l         上面的特殊bean Expando在运行时,动态添加属性

l         它实际上是一个行为象动态beanMap:增加name/value对和等效的getter/setter方法,就象定义一个真正的bean

7)安全导航

l         如果你在访问复杂对象时,不想遇到NullPointerException异常,你可以使用“->”而不是“.”来导航

foo = null
bar = foo->something->myMethod()
assert bar == null

12、字符串

1)基本用法

l         Groovy中的字符串允许使用双引号和单引号

println "he said 'cheese' once"
println 'he said "cheese!" again'

l         Groovy支持\uXXXX引用(其中X16进制数),用来表示特殊字符,例如\u0040@字符相同

2)多行字符串

l         Groovy中的字符串可以分成多行

foo = "hello
 there 
 how are things?"
println(foo)

3Here-docs

l         如果有一大块文本(如HTML的)不想编码,你可以使用Here-docs

name = "James"
text = <<
hello there ${name}
how are you today?
FOO
assert text != null
println(text)

4GString

l         使用${expression}语法,可以在字符串中包含任意的表达式,类似于JSP ELVelocity

l         任何有效的Groovy表达式都能够使用${...}包含到方法调用中

l         使用包含${expression}的字符串时,CString对象就会被创建,以包含在字符串中使用的文本和值

l         CString使用惰性求值方式,只有在调用toString()方法时才会求值

阅读(1460) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~