在使用Java的过程中,和C#的语法相比有些还是比较麻烦,比如异常、get set等问题,毕竟Java的发展时间比C#长了很多,很多问题当初设计时没有考虑到,为了向前兼容,不得不保留一定的历史负担(如泛型的处理,java的擦除法实现就是后续的兼容考虑)。不过最近在一个项目中使用groovy grails感觉很是方便,特别groovy和java的集成十分的方便。
下面把groovy涉及的一些基础知识整理一下,供使用参考,groovy本身的文档也很全面,但篇幅太长,如下作为一个简明的参考。
官网定义:Groovy is an agile dynamic language for the Java Platform with many features that are inspired by languages like Python, Ruby and Smalltalk, making them available to Java developers using a Java-like syntax.
Groovya dynamic language made specifically for the JVM.
Groovy was designed with the JVM in mind
Groovy does not just have access to the existing Java API; its Groovy Development Kit(GDK) actually extends the Java API by adding new methods to the existing Java classes tomake them more Groovy.
Groovy is a standard governed by the Java Community Process (JCP)as Java Specification Request (JSR) 241.
如下涵盖了日常使用中常用的groovy语法,按照这个几次的使用可以很快地熟悉groovy的语法
1. 默认导入的命名空间Automatic Imports |
importjava.lang.*; importjava.util.*; import java.net.*; import java.io.*; import java.math.BigInteger; import java.math.BigDecimal; importgroovy.lang.*; importgroovy.util.*; 使用以上的命名空间下的接口、类等不需要引入 |
2. 可选分号Optional Semicolons |
msg = "Hello" msg = "Hello"; |
3. 可选括号Optional Parentheses |
println("Hello World!") println "Hello World!" //Method Pointer def pizza = new Pizza() def deliver = pizza.&deliver() deliver |
4. 可选返回值Optional Return Statements |
String getFullName(){ return "${firstName} ${lastName}" } //equivalent code String getFullName(){ "${firstName} ${lastName}" } |
5. 可选类型声明Optional Datatype Declaration (Duck Typing) |
s = "hello" def s1 = "hello" String s2 = "hello" printlns.class println s1.class println s2.class |
6. 可选异常处理Optional Exception Handling |
//in Java: try{ Reader reader = new FileReader("/foo.txt") } catch(FileNotFoundException e){ e.printStackTrace() } //in Groovy: def reader = new FileReader("/foo.txt") |
7. 操作符重载Operator Overloading |
Operator Method a == b or a != b a.equals(b) a + b a.plus(b) a - b a.minus(b) a * b a.multiply(b) a / b a.div(b) a % b a.mod(b) a++ or ++a a.next() a- - or - -a a.previous() a & b a.and(b) a | b a.or(b) a[b] a.getAt(b) a[b] = c a.putAt(b,c) a << b a.leftShift(b) a >> b a.rightShift(b) a < b or a > b or a <= b or a >= b a.compareTo(b) |
8. Safe Dereferencing (?) |
s = [1, 2] println s?.size() s = null println s?.size() println person?.address?.phoneNumber //可连用不用检查空 |
9. 自动装箱Autoboxing |
autoboxes everything on the fly float f = (float) 2.2F f.class primitive类型自动装箱 |
10. 真值Groovy Truth |
//true if(1) // any non-zero value is true if(-1) if(!null) // any non-null value is true if("John") // any non-empty string is true Map family = [dad:"John", mom:"Jane"] if(family) // true since the map is populated String[] sa = new String[1] if(sa) // true since the array length is greater than 0 StringBuffersb = new StringBuffer() sb.append("Hi") if(sb) // true since the StringBuffer is populated //false if(0) // zero is false if(null) // null is false if("") // empty strings are false Map family = [:] if(family) // false since the map is empty String[] sa = new String[0] if(sa) // false since the array is zero length StringBuffersb = new StringBuffer() if(sb) // false since the StringBuffer is empty |
11. Embedded Quotes |
def s1 = 'My name is "Jane"' def s2 = "My name is 'Jane'" def s3 = "My name is \"Jane\"" 单双引号都可以表示字符串 |
12. Heredocs (Triple Quotes) |
s ='''This is demo''' println s 三个单、双引号 |
13. GStrings |
def name = "John" println "Hello ${name}. Today is ${new Date()}" |
14. List/Map Shortcuts |
def languages = ["Java", "Groovy", "JRuby"] printlnlanguages.class def array = ["Java", "Groovy", "JRuby"] as String[] def set = ["Java", "Groovy", "JRuby"] as Set def empty = [] printlnempty.size() languages << "Jython" println languages[1] printlnlanguages.getAt(1) languages.each{println it} languages.each{lang -> printlnlang } languages.eachWithIndex{lang, i -> println "${i}: ${lang}" } languages.sort() languages.pop() languages.findAll{ it.startsWith("G") } languages.collect{ it += " is cool"} //Spread Operator (*) println languages*.toUpperCase() def family = [dad:"John", mom:"Jane"] family.get("dad") printlnfamily.dad family.each{k,v -> println "${v} is the ${k}" } family.keySet() import groovy.sql.Sql //Spread Operator (*) defparams = [] params<< "jdbc:mysql://localhost:3306/test" params<< "root" params<< "" params<< "com.mysql.jdbc.Driver" printlnparams defsql = Sql.newInstance(*params) //defdb = [url:'jdbc:hsqldb:mem:testDB', user:'sa', password:'', driver:'org.hsqldb.jdbcDriver'] //defsql = Sql.newInstance(db.url, db.user, db.password, db.driver) defsql = groovy.sql.Sql.newInstance('jdbc:mysql://localhost:3306/tekdays', "root", '', 'com.mysql.jdbc.Driver') printlnsql.connection.catalog mysql-connector-java-5.0.7-bin.jar放到groovy安装lib目录下 |
15. Ranges |
def r = 1..3 (1..3).each{println "Bye"} def today = new Date() defnextWeek = today + 7 (today..nextWeek).each{println it} |
16. Closures and Blocks |
def hi = { println "Hi"} hi() def hello = { println "Hi ${it}" } hello("John") defcalculateTax = { taxRate, amount -> return amount + (taxRate * amount) } println "Total cost: ${calculateTax(0.055, 100)}" //预绑定 defcalculateTax = { taxRate, amount -> return amount + (taxRate * amount) } def tax = calculateTax.curry(0.1) [10,20,30].each{ println "Total cost: ${tax(it)}" } |
篇幅有些长,不过有了这些知识对深入的groovy grails的使用很有裨益。