Groovy
Groovy中的循环
for(i in 0..2) {println "hello"}
将会输出
hello
hello
hello
下面两句等价
1.upto(3,{println "$it"})
1.upto(3) {println "$it"} //当闭包是函数的最后一个参数可以写在函数外面
输出
1
2
3
循环10次
10.times {
println "hello"+it
}
从0开始每次增长2
0.step(11,2){println it}
输出
0
2
4
6
8
10
Groovy中的操作符
安全导航操作符
举例:
def foo(String str){
println str?.reverse()
}
foo("hello")
foo(null)
输出:
olleh
null
?.操作符只有在引用不为null时才会调用指定的方法和属性,这有点跟kotlin想象
异常的处理
Groovy不强制处理异常,会自动向上传,传给最上层的调用,如:
def openfile(String fileName){
new FileInputStream(fileName)
}
openFile并没有处理FileNotFoundException异常,如果产生了改异常,它并不会被压制下来。相反他会传递给调用代码,由调用代码来处理。
try{
openfile("fileName")
}catch(FileNotFoundException ex){
//在这里处理异常
}
如果有兴趣捕获所有的异常Exception也可以省略异常的类型
try{
openfile("fileName")
}catch(ex){
//在这里处理异常
}
如果想要捕获Exception之外的Error和Throwable,需要使用catch(Throwable t)
JavaBean
Groovy中的javabean不要求写setters和getters,groovy会自动为我们创建
class Car{
def miles = 0 //def声明一个属性
final year; //final修饰的字段不能更改
Car(theyear){
year = theyear
}
}
Groovy的实现不区分public、private、protected,即使变量加了private修饰,外接还可以可以访问,因为自动生成了getter方法
Groovy 特性
静态方法内可以使用this来引用Class对象,在下面的例子中,learn()方法返回的是Class对象,所以可以使用链式调用
class Wizard{
def static learn(trick,action){
....
this
}
}
Wizard.learn("hello",{})
.learn("")
.learn("")