Groovy (一)快速撸一下groovy 基础

作者: zcwfeng | 来源:发表于2020-12-07 12:12 被阅读0次
    • Groovy开发环境配置

    官网 自行配置,简单无法形容。

    • 变量与字符串

    注意点:弱类型定义必须赋值

    // 强类型
    //int x=1
    //double y=3.14
    //char ch='a'
    //boolean flag = true
    
    //class java.lang.Integer
    //class java.lang.Double
    //class java.lang.Character
    //class java.lang.Boolean
    
    // 弱类型,必须赋值
    
    def x=1
    def y=3.14
    def ch='a'
    def flag = true
    
    //class java.lang.Integer
    //class java.math.BigDecimal
    //class java.lang.String
    //class java.lang.Boolean
    x = 'david'
    y = "david"
    ch = '''david'''
    
    println x.class
    println y.class
    println ch.class
    
    println "${ch} name"
    println flag.class
    
    
    // groovy 中String的api
    def string = 'hello'
    def string2 = 'Hello'
    def string3 = 'el'
    
    println string > string2
    println string[1..2]
    println string.minus(string3)
    println string .reverse()
    println string.capitalize()
    
    • 闭包语法

    很多语言都有闭包,和kotlin对比学

    // 定义与使用,无参数闭包
    //def closure = {
    //    println "hello groovy!"
    //}
    
    //closure()
    //closure.call()
    
    // 带参数的闭包
    
    //def closure={String name,int age->
    //    println "hello ${name}:age ${age}"
    //}
    //
    //closure.call("David",10)
    
    // 带默认参数
    def closure = {
        println "hello ${it}"
        return "123"
    }
    
    def result = closure.call("David")
    println "result=" + result
    
    /**
     * 匿名内联函数,也称为一个闭包。
     * 基本类型相关的API
     */
    
    int x = fab(5)
    int fab(int number){
        int result =1;
        1.upto(number,{num-> result *= num})
        return result
    }
    println x
    
    int fab2(int number){
        int result = 1
        number.downto(1){
            num -> result *= num
        }
        return result
    }
    int y = fab2(5)
    println y
    
    int sum(int number) {
        int result = 0
        number.times  {
            num -> result += num
        }
        return result
    }
    
    def z = sum(5)
    println(z)
    
    • 闭包语法基本使用

    String 相关。find,findAll,any,every,collect 很多地方都有这个语法糖

    def str =  "2 and 3 is 5"
    
    //str.each {
    //    String s -> print s.multiply(2)
    //}
    
    println str.find{
        String s ->s.isNumber()
    }
    
    def list = str.findAll{
        String s ->s.isNumber()
    
    }
    printf list.toListString()
    
    def result = str.any {
        String s -> s.isNumber()
    }
    println result
    
    def every = str.every {
        String s -> str.isNumber()
    }
    println every
    
    def lis = str.collect{
        it.toUpperCase()
    }
    println lis
    

    闭包三个变量,this,owner,delegate

    /**
     * 闭包的三个变量,this,owner,delegate
     * 同一个闭包中,都是相同对象
     */
    //def scriptClosurer={
    //    println this
    //    println owner
    //    println delegate
    //}
    //scriptClosurer.call()
    
    //class Person{
    //    def static classClosurer={
    //        println "classClosure:" + this
    //        println "classClosure:" + owner
    //        println "classClosure:" + delegate
    //    }
    //
    //    def static method(){
    //        def classtClosurer={
    //            println "methodclassClosure:" + this
    //            println "methodclassClosure:" + owner
    //            println "methodclassClosure:" + delegate
    //        }
    //        classtClosurer.call()
    //    }
    //
    //}
    //Person.classClosurer.call()
    //Person.method()
    
    // 闭包内的闭包
    //def nestClosure = {
    //    def innerClosurer={
    //        println this
    //        println owner
    //        println delegate
    //    }
    //    innerClosurer.call()
    //}
    //
    //nestClosure.call()
    
    //class Person{}
    //Person p = new Person()
    //def nestClosure = {
    //    def innerClosurer={
    //        println this
    //        println owner
    //        println delegate
    //    }
    //    innerClosurer.delegate = p
    //    innerClosurer.call()
    //}
    //
    //nestClosure.call()
    
    class Student{
        String name
        def pretty={"My name is ${name}"}
        String toString(){
            pretty.call()
        }
    }
    def student = new Student(name:"David")
    
    class Teacher{
        String name
    }
    def teacher = new Teacher(name:"andy")
    student.pretty.delegate =  teacher
    //闭包的委托策略
    student.pretty.resolveStrategy = Closure.DELEGATE_FIRST
    println student.toString()
    

    Closure 的策略

    /**
     * 闭包的三个变量,this,owner,delegate
     * 同一个闭包中,都是相同对象
     */
    //def scriptClosurer={
    //    println this
    //    println owner
    //    println delegate
    //}
    //scriptClosurer.call()
    
    //class Person{
    //    def static classClosurer={
    //        println "classClosure:" + this
    //        println "classClosure:" + owner
    //        println "classClosure:" + delegate
    //    }
    //
    //    def static method(){
    //        def classtClosurer={
    //            println "methodclassClosure:" + this
    //            println "methodclassClosure:" + owner
    //            println "methodclassClosure:" + delegate
    //        }
    //        classtClosurer.call()
    //    }
    //
    //}
    //Person.classClosurer.call()
    //Person.method()
    
    // 闭包内的闭包
    //def nestClosure = {
    //    def innerClosurer={
    //        println this
    //        println owner
    //        println delegate
    //    }
    //    innerClosurer.call()
    //}
    //
    //nestClosure.call()
    
    //class Person{}
    //Person p = new Person()
    //def nestClosure = {
    //    def innerClosurer={
    //        println this
    //        println owner
    //        println delegate
    //    }
    //    innerClosurer.delegate = p
    //    innerClosurer.call()
    //}
    //
    //nestClosure.call()
    
    class Student{
        String name
        def pretty={"My name is ${name}"}
        String toString(){
            pretty.call()
        }
    }
    def student = new Student(name:"David")
    
    class Teacher{
        String name
    }
    def teacher = new Teacher(name:"andy")
    student.pretty.delegate =  teacher
    //闭包的委托策略
    student.pretty.resolveStrategy = Closure.DELEGATE_FIRST
    println student.toString()
    
    • 常用数据结构

    List 基本操作

    package collect
    
    def list = [1,2,3,4,5]
    println list.class
    println list.size()
    def array=[1,2,3,4,5] as int[]
    
    list.add(6)
    list << 2
    
    println list
    def plusList = list + 5
    println plusList
    
    plusList.add(3,9)
    println plusList
    
    //list.remove(2)
    //println list
    //
    //list.removeElement(2)
    //println list
    
    list.removeAll{
        return it%2 != 0
    }
    
    println list
    
    def findList=[5,-3,1,4]
    int result =  findList.find{
        return it %2 != 0
    }
    println result
    
    def result2 =  findList.any{
        return it %2 != 0
    }
    
    println result2
    

    Map 基本操作

    package collect
    
    //def colors=[red:'ff0000',green:'00ff00',blue:'0000ff']
    //println(colors.getClass())
    //
    //println(colors.red)
    //println colors.red
    //
    //colors.yellow ='ffff00'
    //println colors
    //
    //colors.map=[key1:1,key2:2]
    //
    //println colors.toMapString()
    
    def teachers = [
            1: [number: 001, name: "Jetty"],
            2: [number: 002, name: "David"]
    ]
    teachers.each {
        def key, def value ->
            println "key=${key}----value=${value}"
    }
    
    teachers.each {
        def teacher ->
            println "key=${teacher.key}----value=${teacher.value}"
    }
    
    teachers.eachWithIndex {
        def teacher, int index ->
            println "index=${index}---key=${teacher.key}----value=${teacher.value}"
    }
    
    def entry = teachers.find {
        def teacher ->
            {
                return teacher.value.name == "David"
            }
    }
    
    println entry
    
    
    def number = teachers.findAll {
        def teacher ->
            {
                return teacher.value.name == "David"
            }
    }.collect {
        return it.value.number
    }
    
    println number.toListString()
    
    // 分组 查询
    
    def group = teachers.groupBy {
        def teacher ->
            return teacher.value.name == "David" ? "group1" : "group2"
    }
    
    println group.toMapString()
    //排序 map返回一个新的map list 原来listt中进行排序
    def sort = teachers.sort {
        def t1, def t2 ->
            return t1.key > t2.key ? 1 : -1
    }
    println sort.toMapString()
    

    Range 基本操作,相当于轻量级的List

    package collect
    
    import org.testng.IResultMap
    
    //定义 Range 相当与轻量级的Range
    def range = 1..10
    
    println range[0]
    println range.contains(8)
    println range.from
    println range.to
    //遍历
    range.each {
        println it
    }
    for (i in range) {
        println i
    }
    
    def getGrade(Number score) {
        def result
        switch (score) {
            case 0..<60:
                result = '不及格'
                break
            case 60..100:
                result = '合格'
                break
            default:
                result = '输入 异常'
    
        }
    }
    getGrade(100)
    
    • 面向对象

    和java很像,trait,interface,class------trait 介于 interface 和 abstract之间
    interface Action

    package objectoration
    
    interface Action {
        void eat()
    
        void drink()
    
        void play()
    }
    

    trait

    package objectoration
    
    trait DefaultAction {
        abstract void eat()
        void play(){
            println 'i can play'
        }
    }
    

    class Person

    package objectoration
    //1.groovy 所有类型public
    //2.groovy 所有类GroovyObject
    class Person implements Action,DefaultAction{
        String name
        int age
        def increateseAge(Integer year){
            this.age += year
        }
    
        @Override
        void eat() {
    
        }
    
        @Override
        void drink() {
    
        }
    
    
    }
    
    
    

    测试

    package objectoration
    
    def person=new Person(name:'jetty',age:18)
    println person.name + " " + person.age
    println person.getName()
    person.increateseAge(1)
    println person.getAge()
    person.play()
    
    • JSON 与 XML 解析

    JSON 的基本,操作,Person类和上面一致

    package jsonstudy
    
    import groovy.json.JsonOutput
    import groovy.json.JsonSlurper
    
    def list = [
            new Person(name:'David',age:18),
            new Person(name:'Marry',age:18)
    ]
    //转成json字符串
    println JsonOutput.toJson(list)
    // 格式化
    def json = JsonOutput.toJson(list)
    println JsonOutput.prettyPrint(json)
    
    //
    def jsonSluper = new JsonSlurper()
    def object = jsonSluper.parse("[{\"age\":18,\"name\":\"David\"},{\"age\":18,\"name\":\"Marry\"}]".getBytes())
    println object
    def object2 = jsonSluper.parse("[{\"abc\":\"David\"}]".getBytes())
    println object2.abc
    

    XmlSlurper,MarkupBuilder 解析和生成demo基础

    package xmlstudy
    
    import groovy.xml.MarkupBuilder
    import groovy.xml.MarkupBuilderHelper
    import groovy.xml.XmlSlurper
    final String xml = '''
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="top.zcwfeng.opengl">
        <test>test</test>
        <application
            android:name=".App"
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".OpenGLSample01Activity"></activity>
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
        <uses-permission android:name="android.permission.CAMERA"/>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    </manifest>
    '''
    def xmlSluper = new XmlSlurper()
    def result = xmlSluper.parseText(xml)
    println result.@package
    println result.test.text()
    println result.application.@'android:theme'
    result.application.activity.each{
        activity->
            println activity.@'android:name'
    }
    def sw=new StringWriter()
    def xmlBuilder= new MarkupBuilder(sw)
    xmlBuilder.html(){
        title(id:'123',name:'android','xml 生成'){
            person()
        }
        body(name:'java'){
            activity(id:'001',class:'MainActivity','ab')
            activity(id:'001',class:'SecondActivity','abc')
    
        }
    }
    println sw
    
    
    • 文件操作

    文件基本读写

    package fileoperator
    
    def file = new File("/Users/zcw/dev/workspace_android/temp/GroovyDemo/src/fileoperator/fileoperator.groovy")
    
    //file.eachLine {
    //    line ->
    //        println line
    //}
    
    //返回所有文本
    //def text = file.text
    //println text
    
    // list <String>
    //def textList = file.readLines()
    //println textList.toListString()
    
    //java 流的方式
    def reader = file.withReader { reader ->
        char[] buffer = new char[100]
        reader.read(buffer)
        return buffer
    }
    println reader
    
    // 写入
    //file.withWriter {
    //    writer->
    //        writer.write("abc")
    //}
    

    gradle 生命周期

    Initial parse---> Hook ---> Configuration ---> Hook ---> Executeion Parse ---> Hook

    •首先是初始化阶段。对我们前面的multi-project build而言,就是执行settings.gradle
    • Initiliazation phase的下一个阶段是Configration阶段。
    • Configration阶段的目标是解析每个project中的build.gradle。比如multi-project build例子中,解析每个子 目录中的build.gradle。在这两个阶段之间,我们可以加一些定制化的Hook。这当然是通过API来添加的。
    • Configuration阶段完了后,整个build的project以及内部的Task关系就确定了。Configuration会建立一个有向 图来描述Task之间的依赖关系。所以,我们可以添加一个HOOK,即当Task关系图建立好后,执行一些操作。
    • 最后一个阶段就是执行任务了。当然,任务执行完后,我们还可以加Hook。

    生命周期监听的设置有两种方法:
    1.实现一个特定的监听接口;
    2.提供一个用于在收到通知时执行的闭包。

    Project 提供的一些生命周期回调方法:
    •afterEvaluate(closure);
    •afterEvaluate(action);
    •beforeEvaluate(closure);
    •beforeEvaluate(action);

    Gradle 提供的一些生命周期回调方法:
    •afterProject(closure),afterProject(action)
    •beforeProject(closure),beforeProject(action)
    •buildFinished(closure),buildFinished(action)
    •projectsEvaluated(closure),projectsEvaluated(action)
    •projectsLoaded(closure),projectsLoaded(action)
    •settingsEvaluated(closure),settingsEvaluated(action)
    •addBuildListener(buildListener)
    •addListener(listener)
    •addProjectEvaluationListener(listener)

    gradle project

    Gradle为每个build.gradle都会创建一个相应的Project领域对象,在编写Gradle脚本时,我们实际上是在操作
    诸如Project这样的Gradle领域对象

    所有.gradle的文件都可以编写Groovy代码

    相关文章

      网友评论

        本文标题:Groovy (一)快速撸一下groovy 基础

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