groovy用戶指南.doc_第1頁
groovy用戶指南.doc_第2頁
groovy用戶指南.doc_第3頁
groovy用戶指南.doc_第4頁
groovy用戶指南.doc_第5頁
已閱讀5頁,還剩21頁未讀, 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認領(lǐng)

文檔簡介

集合(1)List (java.util.List)list = 1, 2, hello, new java.util.Date()assert list.size() = 4assert list.get(2) = hello注意:一切都是對象(數(shù)字會自動轉(zhuǎn)換)(2)Map (java.util.Map)map = name:James, location:Londonassert map.size() = 2assert map.get(name) = James(3)遍歷集合list = 1, 2, 3for (i in list) println i 2、 閉包(Closures)l 閉包類似Java的內(nèi)類,區(qū)別是閉包只有單一的方法可以調(diào)用,但可以有任意的參數(shù)closure = param - println(hello $param) closure.call(world!)closure = greeting, name - println(greeting + name) closure.call(hello , world!)l 閉包用“”括起,“-”前面是參數(shù),后面是處理語句,使用call調(diào)用l 第一個例子演示了在字符串內(nèi)使用參數(shù)的形式:$param l 第二個例子演示了多參數(shù)形式:用“,”分隔參數(shù)l 如果只有一個參數(shù),可以不寫,而使用缺省的參數(shù)“it”,如下面的例子:closure = println hello + it closure.call(world!)3、 eachl 遍歷集合,逐個傳遞給閉包1, 2, 3.each item - print $item- l 上面例子的輸出結(jié)果是:1-2-3-4、 collectl 遍歷集合,逐個傳遞給閉包,處理后的結(jié)果返回給對應的項value = 1, 2, 3.collect it * 2 assert value = 2, 4, 6與each區(qū)別:value2 = 1, 2, 3.each it * 2 println value2value3 = 1, 2, 3.collect it * 2 println value3結(jié)果:1, 2, 32, 4, 6返回值不同5、 findl 根據(jù)閉包斷言,返回集合中找到的第一個項目value = 1, 2, 3.find it 1 assert value = 26、 findAlll 根據(jù)閉包斷言,返回集合中所有找到的項目value = 1, 2, 3.findAll it 1 assert value = 2, 37、 injectl 遍歷集合,第一次將傳遞的值和集合項目傳給閉包,將處理結(jié)果作為傳遞的值,和下一個集合項目傳給閉包,依此類推value = 1, 2, 3.inject(counting: ) str, item - str + item assert value = counting: 123value = 1, 2, 3.inject(0) count, item - count + item assert value = 68、 everyl 如果集合中所有項目都匹配閉包斷言,就返回true,否則返回falsevalue = 1, 2, 3.every it item 2 assert valuevalue = 1, 2, 3.any item | item 3 assert value = false10、 min/maxl 返回集合中的最小/最大項目(對象必須可比較)value = 9, 4, 2, 10, 5.max()assert value = 10value = 9, 4, 2, 10, 5.min()assert value = 2value = x, y, a, z.min()assert value = a11、 joinl 連接集合中的值成一個字符串value = 1, 2, 3.join(-)assert value = 1-2-312、 yieldl 在Python和Ruby中通過yield語句創(chuàng)建“yield”風格的iterators,在Groovy同樣有效,只是使用的是閉包class Foostatic void main(args) foo = new Foo()for (x in foo.myGenerator) print($x-)myGenerator(Closure yield) yield.call(A)yield.call(B)yield.call(C)l 例子的輸出結(jié)果是:A-B-C-l Cloures原型可以省略,call和括號同樣可選,這樣更象Python/Rubyclass Foo myGenerator(yield) yield Ayield Byield C static void main(args) foo = new Foo()foo.myGenerator println Called with $it 1.閉包先解釋一下閉包的概念:閉包是很多動態(tài)語言提供的一個很方便的功能,它有點像Java中的內(nèi)部類,不同的是閉包中只有一個方法,但這個方法可以有任意個參數(shù)。下面看一個閉包的最簡單的例子:def closure= param - println hello $param closure.call(world!)def是一個關(guān)鍵字,相當于JavaScript中的Var,用來定義一個對象。closure為閉包的名字。在大括號里面,參數(shù)和處理參數(shù)的語句用-隔開。param是這個閉包的參數(shù),參數(shù)的數(shù)目是任意的,不同的參數(shù)之間用,隔開。下面處理這些參數(shù)的語句就可以直接調(diào)用這些參數(shù)了。所有的閉包都是繼承自groovy.lang.Closure類,閉包也是一個普通的類,只是在Groovy中,這個語法比較特別。所以閉包也可以當作一個返回值?;蛘弋斪饕粋€參數(shù)傳入一個方法。閉包的返回值:調(diào)用閉包的call方法,會有一個返回值,可以調(diào)用return來指定,如果不指定的話,則返回閉包中最后一條有返回值的語句。閉包可以調(diào)用的對象:在方法里面,可以調(diào)用方法內(nèi)的局部變量作為類變量,可以調(diào)用類變量關(guān)于0個參數(shù)以及對象it:參數(shù)可以是任意個,沒有參數(shù)就不需要-了。沒有參數(shù)的話,但是傳入了一個參數(shù),這個參數(shù)可以通過一個無類型的對象it來訪問。比如上面的例子我們可以這么寫:def closure2= println hello $it closure2.call(world!)關(guān)于閉包的調(diào)用:定義以后就可以調(diào)用這個閉包,有兩種方式,closure.call(world!)closure(world!)這兩種是沒有任何區(qū)別的,第二個是第一個的簡寫2.集合的本地化語法這個比閉包更容易理解,Groovy對collections, lists, maps, arrays的聲明和使用提供了語言級的支持,可以直接聲明一個list和map,無需調(diào)用new方法創(chuàng)建一個List或者map對象??匆粋€來自Groovy官方網(wǎng)站的例子:def list = 5, 6, 7, 8assert list.get(2) = 7assert list2 = 7assert list instanceof java.util.Listdef emptyList = assert emptyList.size() = 0emptyList.add(5)assert emptyList.size() = 1與Java的區(qū)別如下:1.通過value.的方式來聲明2.通過listindex的方式來訪問和賦值3.通過來聲明一個空的map看一個Map的例子:def map = name:Gromit, likes:cheese, id:1234assert map.get(name) = Gromitassert map.get(id) = 1234assert mapname = Gromitassert mapid = 1234assert map instanceof java.util.Mapdef emptyMap = :assert emptyMap.size() = 0emptyMap.put(foo, 5)assert emptyMap.size() = 1assert emptyMap.get(foo) = 5與Java的區(qū)別如下:1.通過name:value.的方式來聲明2.通過mapname的方式來訪問和賦值3.通過的方式來訪問和賦值4.通過:來聲明一個空的mapRange的使用:Range是Groovy新添的一個集合類,繼承自java.util.List,所以可以像使用List一樣使用。下面是關(guān)于Range的一個例子:def range = 5.8assert range.size() = 4assert range.get(2) = 7assert range2 = 7assert range instanceof java.util.Listassert range.contains(5)assert range.contains(8)range = 5.8assert range.size() = 3assert range.get(2) = 7assert range2 = 7assert range instanceof java.util.Listassert range.contains(5)assert ! range.contains(8)幾個說明1.Range的類型可以是int、char2.通過min.max來聲明3.可以像其他集合一樣使用*.操作符號的使用:可以用來使集合中的所有元素都調(diào)用同一個方法,返回一個同等size的ListList list = Rod, Phil, James, Chrisprintln list*.size()String的特殊使用:String在Groovy中可以像char數(shù)組一樣的使用,下面是一個例子:def text = nice cheese gromit!def x = text2assert x = cassert x.class = Stringdef sub = text5.10assert sub = cheese說明:1.通過textindex的方式返回在index處的字符,不過返回的是string類型的,非char類型2.通過textmin.max方式來返回子字符串,包含max處的字符,String的subString不包含。3.從這個例子中可以看到,可以使用string來表示String,不一定是string-1、類(1)類l Groovy的類定義和Java類似 方法可以基于類(static)或?qū)嵗?可以為public、protected或private 支持常用的Java修飾符,如synchronizedl Groovy的不同地方:缺省是publicl Groovy支持JavaBean機制:GroovyBeanl 每個Groovy類都是字節(jié)碼/JVM級的Java類,任何方法對Java都是有效的,反之亦然l 你可以指定方法的參數(shù)類型和返回類型,這樣可以在通常的Java代碼中更好的工作l 你可以用上面的方式來實現(xiàn)接口或重載方法l 如果省略方法的類型,就會使用缺省的java.lang.Object(2)腳本l Groovy支持純腳本,而不需要聲明類,如Foo.groovy包含下面的腳本:println Nice cheese Gromit!l 運行腳本的過程: 編譯成Foo.class(還會有一些內(nèi)類),該類擴展groovy.lang.Script 執(zhí)行自動生成的main方法 實例化Foo類 調(diào)用run方法執(zhí)行腳本內(nèi)容l 可以在Java代碼中執(zhí)行腳本,同時還可以傳遞變量值到腳本中l(wèi) Foo.groovy內(nèi)容修改如下println Nice $cheese Gromit!l 下面是執(zhí)行腳本的UseFoo類import groovy.lang.Binding;import groovy.lang.Script;public class UseFoo public static void main(String args) Binding binding = new Binding();binding.setVariable(cheese, Cheddar);Script foo = new Foo(binding);foo.run();l UseFoo運行的結(jié)果是:Nice Cheddar Gromit!l 執(zhí)行腳本的方法是創(chuàng)建Foo類實例,調(diào)用其run方法l Foo類有一個帶Binding參數(shù)的構(gòu)造函數(shù),可以通過Binding類的setVariable方法設置值給腳本中的屬性變量l Foo類有一個不帶參數(shù)的構(gòu)造函數(shù),在不傳遞屬性變量值時使用l 在腳本結(jié)束后,腳本中創(chuàng)建的任何變量都會在Binding中,以供在Java中訪問l 再將Foo.groovy內(nèi)容修改如下println Nice $cheese Gromit!cheese = changedl UseFoo類修改為:import groovy.lang.Binding;import groovy.lang.Script;public class UseFoo public static void main(String args) Binding binding = new Binding();binding.setVariable(cheese, Cheddar);Script foo = new Foo(binding);foo.run();println binding.getVariable(cheese);l UseFoo運行的結(jié)果是:Nice Cheddar Gromit!changed(3)腳本中的函數(shù)l 不同于基于Class的Groovy,純腳本中的函數(shù)用def關(guān)鍵字聲明def foo(list, value) println Calling function foo() with param $value list println(Hello $a $b $c) c(cheese, 234, gromit)l 下面是另一個使用兩個參數(shù)的有用例子,在Groovy快速入門已經(jīng)講過:value = 1, 2, 3.inject(counting: ) str, item str + item assert value = counting: 123value = 1, 2, 3.inject(0) count, item - count + item assert value = 63、集合Groovy支持集合、List、Map和數(shù)組(1)Listsl 下面是創(chuàng)建List的例子,表示空List表達式list = 5, 6, 7, 8assert list.get(2) = 7assert list instanceof java.util.ListemptyList = assert emptyList.size() = 0emptyList.add(5)assert emptyList.size() = 1l 每個List表達式都是java.util.List的實現(xiàn)(2)范圍(Ranges)l Range允許創(chuàng)建連續(xù)值的列表l 由于Range擴展java.util.List,所以Range可以作為List使用l 使用.的Range是包括兩個邊界,使用.的Range只包括開始邊界,而不包括結(jié)束邊界(/我在groovy1.5中不能使用.,如果想建立不包括邊界的范圍,可以使用 range=5.8)/ an inclusive rangerange = 5.8assert range.size() = 4assert range.get(2) = 7assert range instanceof java.util.Listassert range.contains(5)assert range.contains(8)/ lets use an exclusive rangerange = 5.8assert range.size() = 3assert range.get(2) = 7assert range instanceof java.util.Listassert range.contains(5)assert ! range.contains(8)/我在groovy1.5中不能使用.,如果想建立不包括邊界的范圍,可以使用如下range=5.8l Range可以用于實現(xiàn)java.lang.Comparable的Java對象/ an inclusive rangerange = a.dassert range.size() = 4assert range.get(2) = cassert range instanceof java.util.Listassert range.contains(a)assert range.contains(d)assert ! range.contains(e)l Range可以用于循環(huán)遍歷for (i in 1.10) println Hello $i(3)Mapsl 下面是創(chuàng)建Map的例子,:表示空Map表達式map = name:Gromit, likes:cheese, id:1234assert map.get(name) = Gromitassert map.get(id) = 1234assert map instanceof java.util.MapemptyMap = :assert emptyMap.size() = 0emptyMap.put(5, foo)assert emptyMap.size() = 1assert emptyMap.get(5) = fool Map可以象beans一樣操作,但key值(類似屬性名)必須為有效的String標識map = name:Gromit, likes:cheese, id:1234assert = Gromitassert map.id = 1234emptyMap = :assert emptyMap.size() = 0emptyMap.foo = 5assert emptyMap.size() = 1assert emptyMap.foo = 5(4)使用下標操作符l 可以在字符串、Lists、Maps.中使用下標進行索引text = nice cheese gromit!x = text2assert x = cassert x.class = Stringsub = text5.10assert sub = cheesemap = name:Gromit, likes:cheese, id:1234assert mapname = Gromitlist = 10, 11, 12answer = list2assert answer = 12list = 100.200sub = list1, 3, 20.25, 33assert sub = 101, 103, 120, 121, 122, 123, 124, 125, 133l 可以使用下標操作符更新項目list = a, b, clist2 = dlist0 = list1list3 = 5assert list = b, b, d, 5l 可以使用負索引從最后開始計數(shù)text = nice cheese gromit!x = text-1assert x = !name = text-7.-2assert name = gromitl 也可以使用向后范圍(開始索引大于結(jié)束索引),返回的結(jié)果是反轉(zhuǎn)的text = nice cheese gromit!name = text3.1assert name = eci4、與Java的不同(1)通用l 在Groovy中,=等價于equals(),=意味著標識比較(等同Java中的=)好像沒有這個操作符=l 在Java中=意味著原類型的相等和對象的標識比較,如a=b(a和b是指向相同對象的引用)l 傳遞閉包給方法或使用GroovyMarkup時,要和方法的調(diào)用在同一行上,如:(本人嘗試不在同一行也可,但建議遵守要求)1, 2, 3.each println it l 如果要將放在獨立于方法的一行上,要使用括號()1, 2, 3.each ( println it )l 下面的寫法是無效的,會將閉包解釋成獨立的閉包,而不會將閉包作為方法的參數(shù)傳遞1, 2, 3.each println it (2)應該意識到的事情l 語句后面的分號是可選的,但在同一行上有多個語句需要用分號分隔l return關(guān)鍵字可選l 可以在static方法內(nèi)使用_this_關(guān)鍵字(何用?)l 缺省的修飾符是publicl Groovy中的protected等價包的protected和Java的protectedl 補充:方法調(diào)用時,括號是可選的,(注意最好使用括號,以防止錯誤)(3)在Java中無效的Groovy新特性l 閉包l List和Map的本地語法l GroovyMarkup和Gpath的支持l 正則表達式的本地支持l 多形式的iteration和強大的switch語句l 動態(tài)和靜態(tài)類型的支持l 在字符串中嵌入表達式l 增加了許多新的幫助方法l 在屬性和添加事件偵聽方面,簡化了編寫bean的語法5、Groovy Mathl Groovy支持訪問所有的Java Math類和操作l 為了使math操作在腳本編寫時盡可能直觀,Groovy math模型支持文字化math操作l 缺省計算使用的是精確的小數(shù)(BigDecimal),如:1.1 + 0.1 = 1.2返回的是true,而不是false(不象在Java中使用float或double)(1)數(shù)字的文字表示l Groovy的小數(shù)文字表示是java.math.BigDecimal的實例,而不是浮點類型(Float或Double)l Float和Double可以使用后面講的后綴(F和D)方法來創(chuàng)建l 小數(shù)的指數(shù)形式也支持,如12.3e-23l 十六進制和八進制也支持,十六進制前綴0x,八進制前綴0l 整數(shù)類型可以使用后面講的后綴(I、L和G)方法來創(chuàng)建,如果不指定根據(jù)數(shù)值的大小使用合適的類型l 數(shù)字類型的后綴文字表示_Type_Suffix_BigInteger_G_Long_L_Integer_I_BigDecimal_(缺?。Double_D_Float_Fl 例子:assert 42I = newInteger(42);assert 123L = newLong(123);assert 2147483648 = newLong(2147483648); /Long type used, value too large for an Integerassert 456G = new java.math.BigInteger(456);assert 123.45 = new java.math.BigDecimal(123.45); /default BigDecimal type usedassert 1.200065D = newDouble(1.200065);assert 1.234F = newFloat(1.234);assert 1.23E23D = newDouble(1.23E23);(2)Math操作l Groovy的Math實現(xiàn)很接近Java 1.5 BigDecimal Math模型的實踐l Java.lang.Number包括其子類的二元操作(除了除法)會根據(jù)下表自動轉(zhuǎn)換參數(shù)類型_BigDecimal_BigInteger_Double_Float_Long_Integer_BigDecimal_BigDecimalBigDecimalDoubleDoubleBigDecimalBigDecimal_BigInteger_BigDecimalBigIntegerDoubleDoubleBigIntegerBigInteger_Double_DoubleDoubleDoubleDoubleDoubleDouble_Float_DoubleDoubleDoubleDoubleDoubleDouble_Long_BigDecimalBigIntegerDoubleDoubleLongLong_Integer_BigDecimalBigIntegerDoubleDoubleLongIntegerl 注意:Byte、Character、Short都作為Integer類型(3)除法l 除法操作“/”和“/=”在操作數(shù)中有Float或Double類型時,結(jié)果為Double類型;其它情況,結(jié)果為BigDecimal類型l BigDecimal類型的操作會這樣做:BigDecimal.divide(BigDecimal right, , BigDecimal.ROUND_HALF_UP)其中是MAX(this.scale(), right.scale(), 10)l 例子:1/2 = new java.math.BigDecimal(0.5);1/3 = new java.math.BigDecimal(0.3333333333);2/3 = new java.math.BigDecimal(0.6666666667);l 整型除法使用“”和“=”操作,返回整型類型l 由于“”是Java中的轉(zhuǎn)義符,在字符串中使用需要轉(zhuǎn)義 x = 83 (4)數(shù)字文字表示語法IntegerLiteral: Base10IntegerLiteral HexIntegerLiteral OctalIntegerLiteral Base10IntegerLiteral: Base10Numeral IntegerTypeSuffix (optional) HexIntegerLiteral: HexNumeral IntegerTypeSuffix (optional) OctalIntegerLiteral:OctalNumeral IntegerTypeSuffix (optional) IntegerTypeSuffix: one of i I l L g GBase10Numeral: 0 NonZeroDigit Digits (optional) Digits: DigitDigits Digit Digit: 0NonZeroDigitNonZeroDigit: one of1 2 3 4 5 6 7 8 9HexNumeral:0 x HexDigits0 X HexDigitsHexDigits:HexDigitHexDigit HexDigitsHexDigit: one of0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E FOctalNumeral:0 OctalDigitsOctalDigits:OctalDigitOctalDigit OctalDigitsOctalDigit: one of0 1 2 3 4 5 6 7DecimalPointLiteral:Digits . Digits ExponentPart (optional) DecimalTypeSuffix (optional). Digits ExponentPart (optional) DecimalTypeSuffix (optional)Digits ExponentPart DecimalTypeSuffix (optional)Digits ExponentPart (optional) DecimalTypeSuffix (optional) ExponentPart:ExponentIndicator SignedIntegerExponentIndicator: one ofe ESignedInteger:Signopt DigitsSign: one of+ -DecimalTypeSuffix: one off F d D g G6、I/Ol Groovy提供許多有用的方法來處理I/O,包括標準的Java Reader/Writer、InputStream/OutputStream、File和URL類l 使用閉包允許處理資源時確保正確關(guān)閉而不管是否有異常,例如下面的例子遍歷文件的每一行,即使閉包中發(fā)生異常,文件也能正確關(guān)閉:import java.io.Filenew File(foo.txt).eachLine println it l 使用Reader/Writer:通過閉包處理資源import java.io.Filenew File(foo.txt).withReader reader - while (true) line = reader.readLine().l Groovy提供簡單的方法執(zhí)行命令行進程,表達式返回java.lang.Process實例,具有in/out/err流(譯者:沒有測試過)process = ls -l.execute()process.in.eachLine line | println line 7、邏輯分支(1)if-else語句l Groovy提供Java相同的if-else語句x = falsey = falseif ( !x ) x = trueassert x = trueif ( x ) x = false else y = trueassert x = yl Groovy也支持三元操作符y = 5x = (y 1) ? worked : failedassert x = worked(2)switch語句l Groovy的switch語句兼容Java代碼,不同之處在于Groovy的switch語句能夠處理各種類型的switch值,可以做各種類型的匹配:類名,正則,集合,值。 case值為類名匹配switch值為類實例,可為變量,動態(tài) case值為正則表達式匹配switch值的字符串匹配該正則表達式 case值為集合匹配switch值包含在集合中,這包括ranges 除了上面的,case值與switch值相等才匹配x = 1.23result = switch ( x ) case foo: result = found foo case bar: result += bar case 4, 5, 6, inList: result = list break case 12.30: result = range break caseInteger: result = integer break caseNumber: result = number break default: result = defaultassert result = numberl switch語句的工作原理:switch語句在做匹配case值時調(diào)用isCase(switchValue)方法,缺省調(diào)用equals(switchValue),但是已經(jīng)被重載成各種類型,如類,正則表達式、集合等等l 可以創(chuàng)建自定義的匹配類,增加isCase(switchValue)方法來提供自定義的匹配類型8、循環(huán)(1)while和do 循環(huán)l Groovy支持Java相同的while和

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預覽,若沒有圖紙預覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負責。
  • 6. 下載文件中如有侵權(quán)或不適當內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準確性、安全性和完整性, 同時也不承擔用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論