Groovy基礎知識
Gradle是Android Studio中的主流構建工具。Gradle內建的Groovy是的一門JVM語言,最終編譯成class檔案在JVM虛擬機器上執行。

def:在Groovy中,通過def關鍵字來宣告變數和方法,用def宣告的型別Groovy會進行型別推斷。
Groovy的特點
- 語句後面的分號可省略;
- 變數型別和方法引數型別可省略;
- 呼叫方法的圓括號可省略;
- 部分語句中的return可省略;
- 所有的Class型別,可省略後面的.class;
- Class類裡,只要有屬性,就預設有Getter/Setter,可省略之;
- 同一個物件的屬性操作,可用with代替:
示例:
def a = 1;//Groovy動態判斷a型別為整型 def test(){ println("hello world!");//可寫成 println "hello world!" return 1;//可寫成 1;不過建議少用 } Test test = new Test(); test.id = 1; test.name = "test"; //可寫成 test.with{ id = 1 name = "test" }
在Groovy中,型別是弱化的,所有的型別可動態推斷,但型別不對仍會報錯。
Groovy中的資料型別
- Java基本資料型別和物件;
- Closure閉包;
- 加強型的List、Map等集合型別;
- 加強型的File、Stream等IO型別;
單引號字串
def result = 'a'+'b' assert result == 'ab'
單引號字串不支援佔位符插值操作,但可通過"+"直接拼接。
assert斷言,若assert為false則表示異常。
雙引號字串
def test = 'a' def result = "hello, ${test}" assert result.toString() == 'hello, a'
雙引號字串支援站位插值操作,一般用:heavy_dollar_sign:{}或者 :heavy_dollar_sign:表示。:heavy_dollar_sign:{}一般用於替換字串或表示式,:heavy_dollar_sign:一般用於屬性格式,如person.name,name是person的屬性。
def person = [name:'jordon',age:28] def result = "$person.name is $person.age years old" assert result == 'jordon is 28 years old'
三引號字串
def result = ''' line one line two line three '''
三重單引號字串允許字串的內容在多行出現,新的行被轉換為'\n',其他所有的空白字元都被完整的按照文字原樣保留。
加強型的List 和 Map
def array = [1,'a',true] //List中可儲存任意型別 assert array[2] == true assert array[-1] == 'a'//負數索引表示從右向左index array << 2.3 //移位表示add元素 //選取子集合 assert array[1,3] == ['a',2.3] assert array[1..3] == ['a',true,2.3] //定義一個Map def colors = [red:'#FF0000', green:'#00FF00'] assert colors['red'] == '#FF0000' == colors.red def key = 'red' assert colors[(key)] == '#FF000' //可以將一個變數或者類用()包起來作為key
儲存在List中的物件不受型別限制,但Groovy中陣列和Java中類似。Groovy中的Map的key可為任何物件,可以將一個變數或者類用()包起來作為key。
Closure閉包
由{ }包括起來的可執行的程式碼塊或方法指標,可作為方法的引數或返回值,也可以作為一個變數存在。
//宣告多引數閉包 def closureMethod1 = {a,b -> println "the word is ${a}${b}" } //宣告隱含引數it閉包 def closureMethod2 = { println it } //外部呼叫閉包 closureMethod1.call(1,2) closureMethod1(1,2) closureMethod2() //閉包作為方法test的引數呼叫 def test(name,password,Closure closure){ println "it is a method" } test('admin','123456',{ //do something by the Closure })
閉包可以有返回值和引數,多個引數之間以 , 分割,引數和程式碼之間以-> 分割。closureMethod1就是閉包的名字。
如果閉包沒定義引數,則預設隱含一個名為it的引數。
在Android studio中的編譯執行Groovy
task(test){//任務名稱 test println 'this is a good test' //to do something } //執行 命令列 gradle test
在Android Studio下的.gradle檔案內編寫task任務,執行其中的Groovy程式碼。
更多API呼叫可翻閱 Groovy官網的API文件 。