美文网首页Android-gradle
Gradle基础语法Groovy

Gradle基础语法Groovy

作者: Chauncey_Chen | 来源:发表于2018-07-06 17:03 被阅读13次

//强弱类型
int x = 10 //强类型

def var1 = 10 //弱类型

//字符串

//单引号(不可扩展)
def name = 'a single string ' //和java中的 ""字符串是一样的, 他在编译器中使用的还是 java.lang.String 类.

//双引号(可扩展字符串)  ${} 是可扩展表达式,即可以写逻辑
def doubleName = "this is a double String "

def xiaoming = "xiaoming"
def sayHello = "Hello : ${xiaoming}" ///和java中的 ""字符串是不一样的, 他在编译器中使用会是 class org.codehaus.groovy.runtime.GStringImpl,!!! 但是这几种的字符串可以自由转换,工作有编译器处理.

//三引号
def thupleName = '''three 
'single' 
string ''' //三引号 可以不用转义字符\ 来操作. 比如换行,引号等等. 可以直接按照你所要的形式打印输出


String echo(String message) {

    return message
}

println(echo(" i am  echo "))

task variable << {

    // println name
    //println doubleName
    println sayHello
    println sayHello.class

    // println thupleName

}

//字符串方法-- 不进包含 String中的方法,还包含 StringGroovyMethods中的方法-------------------

//填充
def stringApi = "groovy"

println stringApi.center(8, "a") //字符串填充

println stringApi.padLeft(8, "a") //字符串追加到左边 结果: agoovy

//字符串比价
def str2 = "compare"

println stringApi > str2 //unicoin 编码表上的顺序比较大小. 也可以使用compareto

//字符获取
println stringApi[0]  //结果 g
//字符串范围获取
println stringApi[0..2]  //结果 gro

//字符串 减法
println stringApi.minus(str2) //如果有相同字符,就会被减去, 如果没有就会保留原始状态


println stringApi.reverse() //直接将字符串倒序操作 yvoorg

println stringApi.capitalize() //首字母 大写

println stringApi.toLowerCase() //首字母 大写

//其他,直接练习即可

//逻辑控制

//switch case

def s = 1.23
def sResult
switch (s) {
//可以解决Java中instance of 等复杂的方法.
    case 'foo':
        sResult = 'found foo'
        break
    case 'bar':
        sResult = 'found bar'
        break
    case [4, 5, 6, 'list']:
        sResult = 'list' //列表
        break
    case 12..30:
        sResult = 'range' //范围
        break

    case Integer://类型
        sResult = 'Integer'
        break
    default: sResult = 'default'
}


println sResult

//for循环

def fSum = 0

for (i in 0..9) {

    fSum += i

}

fSum = 0

//对list进行循环
for (i in [1, 2, 3, 4, 5, 6]) {
    fSum += i
}
//对map进行循环
for (i in ['a': 1, 'b': 2, 'c': 3]) {
    fSum += i.value
}

//===========闭包==============

//1 ------------基础语法-----------

//
//定义 闭包  拥有自己独立作用域的匿名函数  一段开放的、匿名的代码。
// 有点像匿名内部类. 这里实现匿名内部类, 当其他地方调用这个闭包的时候,会主动吊起这段实现代码
def closer = {
    println 'hello closer'
}

//闭包输出的两种方式

//call方式
closer.call()
//java方式
closer()

//闭包传递参数

def closerParam = { String param1, int param2 ->//闭包的参数
    println "hello closer param1:${param1},param2:${param2}"
}

//闭包输出的两种方式

//call方式
closerParam.call("value1", 2)
//java方式
//closerParam("closerParam")

//闭包默认参数
def closerIt = {
    println "hello closer ${it}" //it为默认参数, 即没有变量,也会有隐士的it参数
}
//call方式
closerIt.call("i am  it")

//闭包一定会有返回值
//
def closerReturn = {
    "hello closer ${it}"

}
//call方式
println closerReturn("i am  closerReturn")

//闭包结合使用
//闭包{}可以放在()参数外面 即({}) 也可以(){}

int cx = 10

//求阶乘
int fab(int number) {
    int result = 1
    1.upto(number, { num -> result *= num })//1为普通变量, 而普通变量有很多方法, 闭包的作用是一个代码块.将代码块放到方法内执行.
    return result
}

println fab(5)

int fab2(int number) {
    int result = 1
    number.downto(1) {
        num -> result *= num
    }
    return result
}

println fab2(5)


int cal(int number) {
    int result = 0
    number.times {
        num -> result += num
    }
    return result
}

//字符串和闭包

String strClosure = "the 2 and 3 is 5"
//each 接收闭包参数 遍历字符串
strClosure.each {
    String temp -> print temp * 2
}

//find来查找  //执照符合条件的第一个
println strClosure.find {
        //find方法必须是boolean类型的返回值
    String temp -> temp.isNumber() //所有比包中的返回值 必须是boolean类型

}

//find来查找  //执照符合条件的第一个
println strClosure.findAll {
        //findAll方法必须是boolean类型的返回值
    String temp -> temp.isNumber() //所有比包中的返回值 必须是boolean类型

}

println strClosure.any {
        //是否包含 闭包中的定义
    String ss -> ss.isNumber()
}

println strClosure.collect {
        //按照闭包的逻辑处理 string后,输出 集合
    String ss -> ss.toUpperCase()
}

//闭包核心 this ,owner, delegate 闭包委托策略
//如果 闭包R中 定义这个三个变量, 则三个值相同
//如果比包R中,定义一个闭包A,再在A中定义三个变量, 则三个值不会相同.this=R对象 ,owner=A对象,delegate=A对象
def scriptClosure = {

    println "this:" + this //代表闭包定义处的类
    println "owner:" + owner //代表闭包定义处的类 或者对象
    println "delegate:" + delegate //代表任意对象,默认和owner一致.只想对象可以任意修改
}
scriptClosure.call()

//定一个内部类
class Person {
    def static classClosure = {

        println "classClosure this:" + this //代表闭包定义处的类
        println "classClosure owner:" + owner //代表闭包定义处的类 或者对象
        println "classClosure delegate:" + delegate //代表任意对象,默认和owner一致.
    }


    def static say() {
        def classClosure = {

            println "method this:" + this //代表闭包定义处的类
            println "method owner:" + owner //代表闭包定义处的类 或者对象
            println "method delegate:" + delegate //代表任意对象,默认和owner一致.
        }
        classClosure.call()
    }

}

Person.classClosure

Person.say()

class Student {
    String name

    def pretty = { "My name is ${name}" }

    String toString() {
        pretty.call()
    }
}

class Teacher {
    String name

    def pretty = { "My name is ${name}" }

    String toString() {
        pretty.call()
    }
}

def stu1 = new Student(name: "Student")
def tea1 = new Teacher(name: "Teacher")

println stu1.toString()

//委托策略resolveStrategy
stu1.pretty.delegate = tea1
stu1.pretty.resolveStrategy = Closure.DELEGATE_FIRST

println stu1.toString()


def list = [6, 2, 8, 5, 47, 6, 2, 12]

//Collections.sort(list)
//lsit 自有api可以使用
println list.sort { a, b ->
    a == b ? 0 : Math.abs(a) < Math.abs(b) ? 1 : -1
}

//对象
def file = new File("build.gradle")



def text = file.getText()

//println text

def reader = file.withReader { reader ->

}
def writer = file.withWriter {

}


def copy(String sourcePath, String destationPath) {
    try {
        //
        File destationFile = new File(destationPath)
        if (!destationFile.exists()) {
            destationFile.createNewFile()
        }

        new File(sourcePath).withReader { reader -> //reader即方法的参数 即代码块中 可以对reader 进行操作
            def lines = reader.readLines()            //该方法withReader内部,会调用closure.call(reader)方法.

            println lines

            */
/*destationFile.withWriter {writer ->
                lines.each {line ->
                    writer.append(line+"\r\n")
                }
            }*//*


        }
        return true


    } catch (Exception e) {
        e.printStackTrace()
    }


}

//def result =copy("build.gradle","build_back.gradle")

//println result


task hello1 {
    // copy("build.gradle","build_back.gradle")
}

//plug 调试 https://blog.csdn.net/ceabie/article/details/55271161

def saveObj(Object obj, String path) {
    try {
        //
        File destationFile = new File(path)
        if (!destationFile.exists()) {
            destationFile.createNewFile()
        }

        destationFile.withObjectOutputStream { out ->
            out.writeObject(obj)
        }

        return true


    } catch (Exception e) {
        e.printStackTrace()
    }


}


def readObj(String path) {
    def object = null
    try {
        //
        def destationFile = new File(path)
        if (!destationFile.exists()) {
            return null
        }

        destationFile.withObjectInputStream {input ->
            object=input.readObject()
        }

        return object


    } catch (Exception e) {
        e.printStackTrace()
    }


}


def student1=new Student("Tom")
saveObj(student1,"person.bin")
println readObj()*/




相关文章

网友评论

    本文标题:Gradle基础语法Groovy

    本文链接:https://www.haomeiwen.com/subject/mijbuftx.html