Top Banner
Groovy, 动动动 ~ Scripting – Effective, Efficient, Groovy Life Mail: oldratlee @gmail.com Blog: http://oldratlee.com 1 06/13/2022
42

Groovy Introduction for Java Programmer

May 10, 2015

Download

Technology

Jerry Lee

introduce the groovy language, and show the advantage.
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Groovy Introduction for Java Programmer

04/11/2023 1

Groovy, 动起来 ~Scripting – Effective, Efficient, Groovy Life

Mail: [email protected]: http://oldratlee.com

Page 2: Groovy Introduction for Java Programmer

04/11/2023 2

1. 接触新事物心态2. Groovy Show

代码小例子,吊你胃口3. Groovy Intro

特性语法简析,带你入门4. 动态语言的原则观念5. 动态语言对我们原有观念

的修正 ( 动态要注意的问题 )

6. Groovy 的资料

讲的内容 / 不讲的内容

1. Groovy 语法详解现在有很多书可以看了

2. 程序员信仰、语言宗教

Page 3: Groovy Introduction for Java Programmer

04/11/2023 3

Groovy 的资料

Groovy 和 Java 的集成、互操作

观念的整理

Groovy 语法简介

Groovy Show

接触新事物心态

相关基础概念

日程

Page 4: Groovy Introduction for Java Programmer

04/11/2023 4

类型 强类型 / 弱类型 动态类型 / 静态类型 脚本编程语言 编译器 / 解释器 闭包 FP

相关基础概念

Page 5: Groovy Introduction for Java Programmer

04/11/2023 5

Shell Python, Perl, Ruby JavaScript PHP AWK, SED

常见常用的脚本

Page 6: Groovy Introduction for Java Programmer

04/11/2023 6

FUDFear 、 Uncertain 、 Doubt 不敢、不知、不信

花释子莫效应 语言宗教、程序员信仰

接触新事物心态( 1 )

( 过度的 ) 拒绝?

( 过度地 ) 坚持已知?

Page 7: Groovy Introduction for Java Programmer

04/11/2023 7

过于激进 没有做足够的成本风险分析调查即采用

接触新事物心态( 2 )

( 过度的 ) 接受?

( 过度地 ) 放弃已知?

Page 8: Groovy Introduction for Java Programmer

04/11/2023 8

要有一个好心态!

什么是好心态?

为什么说是好心态?

我们要一个怎样的心态?(世界观)

即是说 标准是什么?我们要找到一把好尺子。一把照着做不会被颠覆,会和谐,会发展的尺子。

Page 9: Groovy Introduction for Java Programmer

04/11/2023 9

已知事物是基础,是我们系统正常运行基础

不排斥新事物,学习新事物

摸清楚后,在适当的地方使用新事物,提高生产力

在精力分配上采用 20/80 原则

我们怎么行动?(方法论)

Page 10: Groovy Introduction for Java Programmer

04/11/2023 10

Groovy Show - What is Groovy?Groovy is like a super version of Java. It can leverage Java's enterprise capabilities but also has cool productivity features like closures, DSL support, builders and dynamic typing.

Groovy = Java – boiler plate code+ optional dynamic typing+ closures+ domain specific languages+ builders+ meta programming

Page 11: Groovy Introduction for Java Programmer

04/11/2023 11

Show 1 – Less Keyboard Type (1)

Page 12: Groovy Introduction for Java Programmer

04/11/2023 12

Show 1 – Less Keyboard Type (2)

Page 13: Groovy Introduction for Java Programmer

04/11/2023 13

Show 1 – Less Keyboard Type (3)

Page 14: Groovy Introduction for Java Programmer

04/11/2023 14

Show 1 – Less Keyboard Type (4)

Page 15: Groovy Introduction for Java Programmer

04/11/2023 15

Show 1 – Less Keyboard Type (5)

5 行 VS ~30 行!

开发,阅读,测试,修改,维护……

Page 16: Groovy Introduction for Java Programmer

04/11/2023 16

Show 2 – Less Less Less!

Page 17: Groovy Introduction for Java Programmer

04/11/2023 17

Show 2 – Less Less Less!

bike = new BikeGroovyBean( manufacturer:’ 中国东风’ , model:‘X60’, serialNo:‘N80’, status:‘ready’, frame:200, weight:300, cost:3000000)

15 行 VS ~70 行!

没有信息量的 GET/SET 方法

琐碎的 SET 代码行

Page 18: Groovy Introduction for Java Programmer

04/11/2023 18

Show 3 – SQL 操作def sql = groovy.sql.Sql.newInstance( "jdbc:mysql://localhost:3306/mydb", "user", "pswd", "com.mysql.jdbc.Driver")

sql.eachRow("select * from FOOD") { println "${it.name}"}

# 上面不是代码片段,而真正可运行的代码

Page 19: Groovy Introduction for Java Programmer

04/11/2023 19

Show 4 – XML 生成def xml = new groovy.xml.MarkupBuilder()

xml.person(id:99) { firstname("John") lastname("Smith")}

上面代码的运行结果 :<person id='99'><firstname>John</firstname><lastname>Smith</lastname></person>

Page 20: Groovy Introduction for Java Programmer

04/11/2023 20

减少 Keyboard Type 的本质和关键:尽量把软件的偶然复杂度中本质复杂度中去除# 参见《代码大全》《 DDD 》

代码是代码是软件的根,代码的简化意味着所有软件活动的相应简化,这些都是成本。

减少 Type 的能量,这样会减少 CO2 的排放。绿色环境。

少了 Keyboard Type 有什么用?

Page 21: Groovy Introduction for Java Programmer

语言的表达力

摘自《代码大全》摘自《人月神话》编程系统产品 对比 程序 的成本是 9 倍# 代码量的减少带来的成本减少 肯定被“ 9” 放大

Page 22: Groovy Introduction for Java Programmer

04/11/2023 22

对 Groovy 特性和语法简介 和 Java 一致的语法略过

这一节大家看到语法的疑惑时,随时可以问。

Groovy 简介

Page 23: Groovy Introduction for Java Programmer

04/11/2023 23

Automatic Imports◦ import java.lang.*;◦ import java.util.*;◦ import java.net.*;◦ import java.io.*;◦ import java.math.BigInteger;◦ import java.math.BigDecimal;◦ import groovy.lang.*;◦ import groovy.util.*;

Optional Semicolons Optional Parentheses

◦ println("Hello World!")◦ println "Hello World!"

Optional Return Statements◦ String getFullName(){◦ return "${firstName} ${lastName}"◦ }◦ //equivalent code◦ String getFullName(){◦ "${firstName} ${lastName}"◦ }

Optional Datatype Declaration Optional Exception Handling

Groovy – Feature (1)

def metho1(x, y, closure1) {}

method1(x, y, { ...... })method1(x, y) { ...... }method1 x, y, { ...... }

method1(x, y, clos)method1(x, y) clos // ERRmethod1 x, y, clos

Page 24: Groovy Introduction for Java Programmer

04/11/2023 24

Operator Overloading◦ Groovy 支持的运算符◦ http://groovy.codehaus.org/Operators◦ http://groovy.codehaus.org/Operator+Overloading

◦ 例子:◦ 10 ** 3 = 1000◦ ~”.*http.*” ( 把一个 String 换成一个 Pattern)

Safe Dereferencing◦ s?.size()◦ ===> null

Autoboxing

Groovy – Feature (2)Operator Methoda + b a.plus(b)a - b a.minus(b)a * b a.multiply(b)a ** b a.power(b)a / b a.div(b)a % b a.mod(b)a | b a.or(b)a & b a.and(b)a ^ b a.xor(b)a++ or ++a a.next()a-- or --a a.previous()a[b] a.getAt(b)a[b] = c a.putAt(b, c)a << b a.leftShift(b)a >> b a.rightShift(b)switch(a){ case(b): } b.isCase(a)~a a.bitwiseNegate()-a a.negative()+a a.positive()a == b a.equals(b) or a.compareTo(b) == 0 **a != b ! a.equals(b)a <=> b a.compareTo(b)a > b a.compareTo(b) > 0a >= b a.compareTo(b) >= 0a < b a.compareTo(b) < 0a <= b a.compareTo(b) <= 0

Page 25: Groovy Introduction for Java Programmer

04/11/2023 25

5/3 = 1.66666667 5.intdiv(3) = 1

类型后缀 G java.math.BigInteger 55G L java.lang.Long 55L I java.lang.Integer 55I G java.math.BigDecimal 3.14G D java.lang.Double 3.14D F java.lang.Float 3.14F

Groovy – Feature (3)

Page 26: Groovy Introduction for Java Programmer

04/11/2023 26

class X

{

def field

def getField()

{

field += 1

}

}

x = new X()

x.field = 1

println x.@field // 1

println x.field // 2

Groovy – Java field Operator (.@)

Page 27: Groovy Introduction for Java Programmer

04/11/2023 27

lst = [1, 2, 3]

assert [*lst, 4, 5] == [1, 2, 3, 4, 5]

methodFoo(*lst) // 方法调用参数也一样

assert ['cat', 'elephant']*.size() == [3, 8]

parent*.action //equivalent to:

parent.collect{ child -> child?.action }

class1*.@field1

m1 = [key1:1, key2:2]

m2 = [*:m1, key3:3] // map 的展开====> [key1=1, key2=2, key3=3]

Groovy – Spread Operator (* *. *.@)

Page 28: Groovy Introduction for Java Programmer

04/11/2023 28

m2 = System.&clearProperty // 静态方法===> org.codehaus.groovy.runtime.MethodClosure@4c61a7e6

m2(“foo”)

class X {

def doSomething() { println "hello" }

}

def obj = new X()

def methRef = obj.&doSomething // 成员方法methRef()

Groovy – Method Reference (.&)

Page 29: Groovy Introduction for Java Programmer

04/11/2023 29

def matcher = "cheesecheese" =~ /cheese/

assert matcher instanceof Matcher

def m = "foobarfoo" =~ /o(b.*r)f/

assert m[0] == ["obarf", "bar"]

assert m[0][1] == "bar"

assert "2009" ==~ /\d+/ // returns TRUE

assert "holla" ==~ /\d+/ // returns FALSE

assert "holla" ==~ ~/\d+/ // returns FALSE

Groovy – Regular Expression Operators :find (=~) , match (==~)

Page 30: Groovy Introduction for Java Programmer

04/11/2023 30

代码例子

// In Java

if(args != null && args.length > 0){

File dir = new File(args[0]);

}

else{

System.out.println("Usage: ListDir /some/dir/name");

}

//in Groovy:

if(args){

dir = new File(args[0])

}

else{

println "Usage: ListDir /some/dir/name"

}

Groovy – Groovy Truth

Groovy 1.7 能自定义 Groovy Truth 。改写 Object 的 asBoolean() 方法

Page 31: Groovy Introduction for Java Programmer

04/11/2023 31

使用单引号◦ ‘Hello \\ “’ Hello \ ”◦ ‘Hello “W” $name’ Hello “W” $name

使用双引号◦ “Hello \\ ‘” Hello \ ‘◦ “Hello ‘W’ $name” Hello ‘w’ jerry

使用三个引号◦ ‘’’Hello \\ ‘W’ “W”◦ $name’’’ Hello \ ‘W’ “W”\n$name

◦ “”” Hello \\ ‘W’ “W”◦ $name””” Hello \ ‘W’ “W”\njerry

使用 /◦ /Hello”’ \d \/ $name/ Hello”’ \d / jerry

Groovy – String/GString

Page 32: Groovy Introduction for Java Programmer

04/11/2023 32

def languages = ["Java", "Groovy", "JRuby"]

println languages.class

===> java.util.ArrayList

def empty = []

println empty.size()

===> 0

def languages = ["Java", "Groovy", "JRuby"]

languages << "Jython"

===> [Java, Groovy, JRuby, Jython]

def languages = ["Java", "Groovy", "JRuby"]

languages << "Jython"

===> [Java, Groovy, JRuby, Jython]

languages.each{println it}

===>

Java

Groovy

Jruby

Groovy – 集合操作 Listgroovy> languages.join(",")

===> Java,Groovy,JRuby

def others = ["Jython", "JavaScript"]

languages += others

===> [Java, Groovy, JRuby, Jython, JavaScript]

languages -= others

===> [Java, Groovy, JRuby]

languages.sort()

languages.reverse()

languages.pop()

Page 33: Groovy Introduction for Java Programmer

04/11/2023 33

def family = [dad:"John", 'mom':"Jane"]

println family.getClass()

===> java.util.LinkedHashMap

def empty = [:]

println empty.size()

===> 0

def family = [dad:"John", mom:"Jane"]

family.get("dad")

family.dad

===> John

def family = [dad:"John", mom:"Jane"]

family.put("kid", "Timmy")

family.kid2 = "Susie"

===> {dad=John, mom=Jane, kid=Timmy, kid2=Susie}

Groovy – 集合操作 Map

Page 34: Groovy Introduction for Java Programmer

04/11/2023 34

def r = 1..3

println r.class

===> groovy.lang.IntRange

r.each{println it}

===>

1

2

3

def r = 1 ..< 4

===> 1, 2, 3

def today = new Date()

===> Sat Dec 29 23:59:28 MST 2007

def nextWeek = today + 2

===> Sat Jan 05 23:59:28 MST 2008

(today..nextWeek).each{println it}

===>

Sat Dec 29 23:59:28 MST 2007

Sun Dec 30 23:59:28 MST 2007

Mon Dec 31 23:59:28 MST 2007

Groovy – Ranges

Page 35: Groovy Introduction for Java Programmer

04/11/2023 35

def x = 1.23

switch ( x ) {

case "foo“:

println “String foo”

case ~/\d+/:

println “String numbers”

case [4, 5, 6, 'inList']:

println “In List”

case 12..30:

println “In Range”

case Integer:

println “A Integer”

default:

println “Oops!”

}

Groovy – switch

在 Groovy 中,类名表示 class 对象,即Integer == Integer.class

Page 36: Groovy Introduction for Java Programmer

04/11/2023 36

def hi = { println "Hi"}

hi()

===> Hi

def calculateTax = { taxRate, amount ->

return amount + (taxRate * amount)

}

println "Total cost: ${calculateTax(0.055, 100)}"

===> Total cost: 105.500

def tax = calculateTax.curry(0.1)

[10,20,30].each{

println "Total cost: ${tax(it)}"

}

===>

Total cost: 11.0

Total cost: 22.0

Total cost: 33.0

Groovy – Closures

Page 37: Groovy Introduction for Java Programmer

04/11/2023 37

how simple, elegant, and flexible your code is when you take advantage of dynamic typing? But, is this risky business?

• You might mistype the method name when creating one of the helpers.• Without the type information, how do you know what to send to your

method?• What if you send a object(which haven’t the methods) to the method?

Programming with dynamic typing without having the discipline of unit testing is playing with wildfire.

动态语言的原则

Page 38: Groovy Introduction for Java Programmer

04/11/2023 38

Groovy 和 Java 的集成、互操作

Page 39: Groovy Introduction for Java Programmer

04/11/2023 39

http://groovy.codehaus.org/Groovy 的官方网站有超过 1000 面的资料,入门的、深入的。

http://groovy.codehaus.org/groovy-jdk/官方文档, Groovy 对 JDK 的扩展,一般叫 GDK

http://groovy.codehaus.org/gapi/Groovy 的 API文档

Groovy 的资料 – 网络

Page 40: Groovy Introduction for Java Programmer

04/11/2023 40

《 Groovy Programming, An Introduction for jdk Developers 》, 2007出版有中文版:《 Groovy 入门经典》 经典的 Groovy 入门书籍,而且应该是最早出版的 Groovy 书籍,拿来做教材不错。虽然用的老版本的 Groovy ,但是有最基础的内容,在后面的几本书中都没有去讲。

《 Groovy in Action 》, 2007年出版,使用的是 Groovy 1.0-RC-01Groovy实战,早就听说要有中文版出版,但到现在还不见影子。一本入门和进阶的书籍,非常不错,就是有点厚(内容充实嘛)。

《 Groovy Recipes, Greasing the Wheels of jdk 》 2008 ,使用的是 Groovy 1.5.0 , Groovy秘笈,属于 Groovy 进阶读物了,里面关于 Parsing XML 和 Writing XML两章写得相当不错

《 Programming Groovy, Dynamic Productivity for the jdk Developer 》 2008 ,使用的是Groovy 1.5.4 ,也是进阶读物,强烈推荐读这本。

特别是关于第三部MOPping Groovy ,唯一一本详细介绍Groovy元编程的书籍, Groovy秘笈只是简单的介绍,而 Programming Groovy 则非常详细、且通俗易懂。

Groovy 的资料 - Groovy

Page 41: Groovy Introduction for Java Programmer

04/11/2023 41

《 Beginning.Groovy.and.Grails.From.Novice.to.Professional 》 2008 ,使用的是 Groovy 1.5.6 、 grails-1.0 , Groovy 和 Grails由入门到精通

《 The.Definitive.Guide.to.Grails 》 2009年出了第二版中文版: Grails权威指南Guillaume Laforge亲自操刀写的书,难道你能错过吗?中文版去年就电子工业出版社出版。《 Grails in Action 》 2009 ,使用的是 Grails 1.1《 Grails, A Quick-Start Guide 》 2009 ,使用的是 Grails 1.1.1《 Getting Started with Grails 》 中文版: Grails 入门指南 我的评价 Grails 入门指南,薄且通俗易懂

PS :可以看到 2009出了很多本 Grails 的书,从一个方面说明了 Groovy 的

被更广泛的关注和使用。

Groovy 的资料 - Grails

Page 42: Groovy Introduction for Java Programmer

04/11/2023 42

《 Grails Persistence with GORM and GSQL 》 2009 ,只有 150 面。

《 Scripting in jdk:Languages,Frameworks,and Patterns 》 2007

中文版: Java 脚本编程:语言、框架与模式 这本书有比较深入的讨论,在其它书中没有。对 Scriptin API 的介绍,会大大加强的你对 Scripting

能力的认识,开阔你的视野。这本书有一部分是对 Groovy 的介绍,也写的不错。

Groovy 的资料 - 其它