groovy学习5-和java比较

原文链接:http://groovy.codehaus.org/Differences+from+Java

1、groovy中默认会导入以下这几个包,所以没有必要特意去单个地导入:

  • java.io.*
  • java.lang.*
  • java.math.BigDecimal
  • java.math.BigInteger
  • java.net.*
  • java.util.*
  • groovy.lang.*
  • groovy.util.*

2、groovy中==的意思就是equals,如果需要引用比较,则必须要用is方法,A.is(B),但是对于null的比较的话,还是用==,例如A == null

 

3、in是一个关键字,不要定义变量叫in

 

4、声明数组:

java的时候你可以这么做:

int[] a = {1,2,3};

groovy:

int[] a = [1,2,3]

5、for循环

java:

for (int i=0; i < len; i++) {...}

 

groovy:

for (i in 0..len-1) {...}

or 
for (i in 0..<len) {...}

or

len.times {...}


6、分号是可选的

7、return也是可选的
8、可以在静态方法中使用this,指向这个class
9、方法和类默认都是public的
10、protected关键字的意思和在java中的是一样的。。。-_-b
11、groovy不支持内部类,改用闭包了
12、groovy编译器不会检测throws抛出的异常
13、使用未定义的变量,传错误的参数,不会报编译错误
-------------------------
其他一些groovy中新增的特性:
  • closures 闭包
  • native syntax for lists and maps 原生格式的list和map
  • GroovyMarkup and GPath support
  • native support for regular expressions 原生支持正则表达式
  • polymorphic iteration and powerful switch statement
  • dynamic and static typing is supported - so you can omit the type declarations on methods, fields and variables
  • you can embed expressions inside strings
  • lots of new helper methods added to the JDK
  • simpler syntax for writing beans for both properties and adding event listeners
  • safe navigation using the ?. operator, e.g. "variable?.field" and "variable?.method()" - no more nested ifs to check for null clogging up your code
posted @ 2010-04-02 10:51  雪霁霜飞  阅读(368)  评论(0编辑  收藏  举报