Hello Groovy
下面是一个java的Hello Groovy程序
public class HelloGroovyJava {
public static void main(String[] arg){
for(int i = 0; i<3; i++){
System.out.print("ho ");
}
System.out.println("Hello Groovy");
}
}
运行结果为:ho ho ho Hello Groovy
同样的结果用groovy写就简单多了,具体代码如下:
for(i in 0..2){
print "ho "
}
println "Hello Groovy"
运行结果为:ho ho ho Hello Groovy
Groovy实现循环的方式
使用range0..2
for(i in 0..2){
print "$i "
}
运行结果:0 1 2
使用upto()
0.upto(2){
print "$it "
}
运行结果:0 1 2
使用times()
3.times{
print "$it "
}
运行结果:0 1 2
使用 step( )方法
如果你想在循环的时候跳读值, 可以使用 step( )方法:
0.step(10, 2) {
print "$it "
}
运行结果:0 2 4 6 8
快速查看GDK
你可以使用java.lang.Process与系统级进程相互作用.
public class ExecuteProcess {
public static void main(String[] arg){
try {
Process proc = Runtime.getRuntime().exec("groovy -v" );
BufferedReader result = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line;
while((line = result.readLine()) != null)
{
System.out.println(line);
}
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
但是GDK, 却使它意想不到的简单
println "groovy -v".execute().text
运行结果都为:Groovy Version: 2.4.7 JVM: 1.8.0_45 Vendor: Oracle Corporation OS: Windows 7
安全导航操作符
安全导航操作符 (?.). 消除普通的 null检查:
def foo(str) {
if (str != null) {
return str.reverse()
}
str?.reverse()
}
println foo('evil' )
println foo(null)
foo( )方法中的?. 操作符当str不为null时才调用str.reverse().
运行结果:
live
null
在null对象上使用?.,而没有抛 NullPointerException异常.
异常处理
在Java中会强迫你进行异常处理检查. 考虑一个简单的案例: 当你调用 Thread的sleep( ) 方
法.Java 强迫你捕获java.lang.InterruptedException.
这导致了大量空的catch块:
// Java code
try {
Thread.sleep(5000);
} catch(InterruptedException ex) {
// eh? I'm losing sleep over what to do here.
}
空的catch 块比没有进行异常处理更糟糕 .
Groovy 不会强迫你处理异常. 任何异常你都不需要处理,它被传递到高的层次. 这里有个实
例来解答Groovy的异常处理:
def openFile(fileName){
new FileInputStream(fileName)
}
openFile( ) 没有处理臭名昭著的 FileNotFoundException.
假如发生异常, 并不会阻止.而是传递给呼叫代码处理:
try {
openFile("nonexistentfile" )
} catch(FileNotFoundException ex) {
// Do whatever you like about this exception here
println "Oops: " + ex
}
如果你关心所有抛出的异常,你可以写一个catch:
try {
openFile("nonexistentfile" )
} catch(ex) { // Do whatever you like about this exception here
println "Oops: " + ex
}
catch(ex)变量,ex没有使用任何类型,因此,可以捕获任何异常,这里并不是捕获Errors和Throwables以外的Exception,如果需要捕获所有这些异常,可以使用catch(Throwablet).