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
像写作文学小说一样写程序
a smooth transition
a seamless mix-and-match of Groovy and Java
Grais is the Groovy web application framework.
最值得学习的Groovy框架
Chapter 1
Groovy will build on your existing experience and familiarity with the Java platform.
James Strachan inventer of Groovy
在Internet Cafe学习Python的时候,产生了为Java Platform引进类似Python的动态语言特性
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:
带括号的是method call
不带括号的为command call, command call只有在参数极其简单的时候用,比如参数里出现(), []
比如println (1..10).getClass().getName() 容易让人误解。
Groovy自动import
groovy.lang.*
groovy.util.*
java.lang.* (Java已经import)
java.util.*
java.net.*
java.io.*
java.math.BigInteger和java.math.BigDecimal
assert是一个keyword, 而不是Groovy加到java.lang.Object的一个method, 所以
assert (1..10).size() == 11不像command一样有问题
==
测试equality,而不是identity, 即
x == y 等同于Java的 x.equals(y), Java中的x == y在Groovy中为x.is(y)
def keyword means "dynamically typed".
没有def,没有type是指environment binding variables,是global的
groovy File.groovy
File.groovy必须是一个Script,a class with main method, a Runnable或者a GroovyTestCase
GroovyBean: Class with Property, Groovy简化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增加新类,而且为己存在的类增加新的功能。
为己存在的类增加新的功能是怎么实现的?
关键是MetaClass, Groovy Code里所有的Method Call都要都MetaClass.invokeMethod处理。
this.foo() generated as(simplified)
this.getMetaClass().invokeMethod(this, "foo", EMPTY_PARAMS_ARRAY)
这肯定会影响Groovy程序的效率,不知道groovyc优化的效果怎么样? groovyc只是compile time的事情,
无法获得runtime的信息,更会减少优化的机会,如果有JVM来做的话,优化的机会应该更多一些。
evaluate(code)