Groovy in Action
-- DIERK KÖNIG
Source code is a means of communication: from you to the compiler, to other team members, and then back to you.
There is both a technical and a human aspect in this communication.
reveal the programmer’s intent in the code as clearly as possible
Literate Programming
像寫(xiě)作文學(xué)小說(shuō)一樣寫(xiě)程序
a smooth transition
a seamless mix-and-match of Groovy and Java
Grais is the Groovy web application framework.
最值得學(xué)習(xí)的Groovy框架
Chapter 1
Groovy will build on your existing experience and familiarity with the Java platform.
James Strachan inventer of Groovy
在Internet Cafe學(xué)習(xí)Python的時(shí)候,產(chǎn)生了為Java Platform引進(jìn)類(lèi)似Python的動(dòng)態(tài)語(yǔ)言特性
Groovy’s aims
feature rich and Java friendly
Groovy is implemented in Java and Groovy itself.
Agility and Dynamik
DSL: domain specific language
Part 1
Chapter 2
#! shebang
first line comment, to find groovy interpreter
GLS: Groovy Language Specification
Optional parentheses:
帶括號(hào)的是method call
不帶括號(hào)的為command call, command call只有在參數(shù)極其簡(jiǎn)單的時(shí)候用,比如參數(shù)里出現(xiàn)(), []
比如println (1..10).getClass().getName() 容易讓人誤解。
Groovy自動(dòng)import
groovy.lang.*
groovy.util.*
java.lang.* (Java已經(jīng)import)
java.util.*
java.net.*
java.io.*
java.math.BigInteger和java.math.BigDecimal
assert是一個(gè)keyword, 而不是Groovy加到j(luò)ava.lang.Object的一個(gè)method, 所以
assert (1..10).size() == 11不像command一樣有問(wèn)題
==
測(cè)試equality,而不是identity, 即
x == y 等同于Java的 x.equals(y), Java中的x == y在Groovy中為x.is(y)
def keyword means "dynamically typed".
沒(méi)有def,沒(méi)有type是指environment binding variables,是global的
groovy File.groovy
File.groovy必須是一個(gè)Script,a class with main method, a Runnable或者a GroovyTestCase
GroovyBean: Class with Property, Groovy簡(jiǎn)化JavaBean
1. Generating the accessor methods, default visibility => define property, generate get/set(if non final)
2. Simplified access to all Bean(JavaBean and GroovyBean) Bean.property
3. Simplified registration of event handlers
GString with "
GString is not subclass of String, No class can be subclass from String , because String is final.
Numbers are objects, not primitive type
Subscript Operator [ ]
Ranges
1..10, subclass of List
Groovy Class Loader
load class from *.groovy transparently
AST: Abstract Syntax Tree
GDK不僅為JDK增加新類(lèi),而且為己存在的類(lèi)增加新的功能。
為己存在的類(lèi)增加新的功能是怎么實(shí)現(xiàn)的?
關(guān)鍵是MetaClass, Groovy Code里所有的Method Call都要都MetaClass.invokeMethod處理。
this.foo() generated as(simplified)
this.getMetaClass().invokeMethod(this, "foo", EMPTY_PARAMS_ARRAY)
這肯定會(huì)影響Groovy程序的效率,不知道groovyc優(yōu)化的效果怎么樣? groovyc只是compile time的事情,
無(wú)法獲得runtime的信息,更會(huì)減少優(yōu)化的機(jī)會(huì),如果有JVM來(lái)做的話(huà),優(yōu)化的機(jī)會(huì)應(yīng)該更多一些。
evaluate(code)