groovy核心语法

news/2024/5/20 3:24:32 标签: android, gradle, groovy

文章目录

  • groovy中的变量
    • 变量的类型
    • 变量的定义
  • 字符串
      • 转义字符
      • 三引号
      • 双引号:可扩展的字符串
      • String的来源
      • 字符串填充
      • 字符串比较
      • 获取字符
      • 字符串减法
      • 其他方法
  • 逻辑控制
      • switch
      • 对范围的for循环
      • 对List的循环
      • 对Map进行循环
  • 闭包
      • 闭包定义和调用
      • 闭包参数
      • 闭包返回值
      • 与基本类型结合使用
      • 与String结合使用
      • 与数据结构结合使用
      • 与文件结合使用
      • 闭包关键变量
      • 闭包的委托策略
  • 数据结构
    • 列表
    • 映射
    • 范围
  • 面向对象
    • 接口
    • 元编程

groovy_2">groovy中的变量

在这里插入图片描述

变量的类型

int x = 10
double y = 3.14
println x.class
println y.class

打印

class java.lang.Integer
class java.lang.Double

所以groovy中没有基本类型变量的,所有类型都是对象类型。

变量的定义

def x = 10
def y = 3.14
def z = 'Hongx'
println x.class
println y.class
println z.class

打印

class java.lang.Integer
class java.math.BigDecimal
class java.lang.String

定义变量之前并不需要一定提前定义它的变量类型,而通过def去定义,编译器会自动去推断你的变量类型。

def x = 10
println x.class
x = 'hongx'
println x.class

class java.lang.Integer
class java.lang.String

字符串

在这里插入图片描述

def name = 'a single string'
println name.class

class java.lang.String



转义字符

def name = 'a single \'a\' string'
println name

a single ‘a’ string



三引号

def name = '''
one 
two
three
'''
println name

line one
two
three



双引号:可扩展的字符串

def name = "hongx"
println name.class

def sayHello = "Hello ${name}"
println sayHello
println sayHello.class

class java.lang.String
Hello hongx
class org.codehaus.groovy.runtime.GStringImpl

def sum = "the sum is ${2+3}"//可扩展任意表达式
println sum

the sum is 5


def sum = "the sum is ${2+3}"//可扩展任意表达式
println sum.class

def result = echo(sum)
println result
println result.class
String echo(String msg){
    return msg
}

class org.codehaus.groovy.runtime.GStringImpl
the sum is 5
class java.lang.String

说明String和GString这两种字符串类型是可以相互转换和调用的。


String的来源

在这里插入图片描述

字符串填充

def str = "groovy"
println str.center(10,'a')
println str.padLeft(10,'a')
println str.padRight(10,'a')

aagroovyaa
aaaagroovy
groovyaaaa



字符串比较

def str = "groovy"
def str2 = "Hello"
//println str.compareTo(str2)
println str > str2

true


获取字符

def str = "groovy"
println str[0]
println str[0..2]

g
gro

字符串减法

def str = "groovy"
def str2 = "o"
println str - str2
println str.minus(str2)

grovy
grovy


其他方法

def str = "groovy"
println str.reverse()
println str.capitalize()//首字符大写
def str2 = "123456"
println str.isNumber()
println str2.isNumber()

yvoorg
Groovy
false
true

逻辑控制

在这里插入图片描述

switch

def x = 1.23
def result
switch (x) {
    case 'foo':
        result = 'found foo'
        break
    case 'bar':
        result = 'bar'
        break
    case [1.23, 4, 5, 6, 'inlist']: //列表
        result = 'list'
        break
    case 12..30:
        result = 'range' //范围
        break
    case Integer:
        result = 'integer'
        break
    case BigDecimal:
        result = 'big decimal'
        break
    default: result = 'default'
}
println result

list


对范围的for循环

def sum = 0
for (i in 0..9) {
    sum += i
}
println sum

45


对List的循环

sum = 0
/**
 * 对List的循环
 */
for (i in [1, 2, 3, 4, 5, 6, 7, 8, 9]) {
    sum += i
}
println sum

45


对Map进行循环

/**
 * 对Map进行循环
 */
sum = 0
for (i in ['lili': 1, 'luck': 2, 'xiaoming': 3]) {
    sum += i.value
}
println sum

6


闭包

闭包定义和调用

def clouser = { println 'hello groovy'}
clouser.call()

hello groovy

闭包参数

def clouser = { String name -> println "hello ${name}"}
clouser.call('groovy')
clouser('groovy')

hello groovy
hello groovy

箭头之前是参数部分,箭头之后是闭包体。


多个参数

def clouser = { String name ,int age -> println "hello ${name} ${age}"}
clouser.call('groovy',18)
clouser('groovy',18)

hello groovy 18
hello groovy 18


默认参数

def clouser = {  println "hello ${it}"}
clouser.call('groovy')

hello groovy


闭包返回值

def clouser = { String name -> return  "hello ${name}"}
def result = clouser('groovy');
println result;

hello groovy


def clouser = { String name -> println  "hello ${name}"}
def result = clouser('groovy');
println result;

hello groovy
null


与基本类型结合使用

upto使用

//求阶乘
int fab(int number){
    int result = 1
    1.upto(number,{num -> result *= num})
    return result
}
println fab(4)

24

DefaultGroovyMethods的upto源码:

    public static void upto(Number self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
        int self1 = self.intValue();
        int to1 = to.intValue();
        if (self1 > to1) {
            throw new GroovyRuntimeException("The argument (" + to + ") to upto() cannot be less than the value (" + self + ") it's called on.");
        } else {
            for(int i = self1; i <= to1; ++i) {
                closure.call(i);
            }

        }
    }

downto使用

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

也可写成这样:

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

DefaultGroovyMethods的downto源码:

    public static void downto(Number self, Number to, @ClosureParams(FirstParam.class) Closure closure) {
        int self1 = self.intValue();
        int to1 = to.intValue();
        if (self1 < to1) {
            throw new GroovyRuntimeException("The argument (" + to + ") to downto() cannot be greater than the value (" + self + ") it's called on.");
        } else {
            for(int i = self1; i >= to1; --i) {
                closure.call(i);
            }

        }
    }

times使用(累加)

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

5050

DefaultGroovyMethods的times源码

    public static void times(Number self, @ClosureParams(value = SimpleType.class,options = {"int"}) Closure closure) {
        int i = 0;

        for(int size = self.intValue(); i < size; ++i) {
            closure.call(i);
            if (closure.getDirective() == 1) {
                break;
            }
        }

    }

与String结合使用

//字符串与闭包结合使用
String str = 'the 2 and 3 is 5'
str.each {
    String temp -> print temp.multiply(2)
}

tthhee 22 aanndd 33 iiss 55


//字符串与闭包结合使用
String str = 'the 2 and 3 is 5'
println str.each {}

the 2 and 3 is 5


String str = 'the 2 and 3 is 5'
//find来查找符合条件的第一个
println str.find{
    String s -> s.isNumber()
}

2

find源码:

    public static Object find(Object self, Closure closure) {
        BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);
        Iterator iter = InvokerHelper.asIterator(self);

        Object value;
        do {
            if (!iter.hasNext()) {
                return null;
            }

            value = iter.next();
        } while(!bcw.call(new Object[]{value}));

        return value;
    }

def list =  str.findAll{
    String s -> s.isNumber()
}
println list.toListString()

[2, 3, 5]


findAll源码:

    public static Collection findAll(Object self, Closure closure) {
        List answer = new ArrayList();
        Iterator iter = InvokerHelper.asIterator(self);
        return findAll((Closure)closure, (Collection)answer, (Iterator)iter);
    }

println str.any{
    String s -> s.isNumber()
}

true

any源码:

    public static boolean any(Object self, Closure predicate) {
        return any(InvokerHelper.asIterator(self), predicate);
    }

    public static <T> boolean any(Iterator<T> self, @ClosureParams(FirstGenericType.class) Closure predicate) {
        BooleanClosureWrapper bcw = new BooleanClosureWrapper(predicate);

        do {
            if (!self.hasNext()) {
                return false;
            }
        } while(!bcw.call(new Object[]{self.next()}));

        return true;
    }

println str.every{
    String s -> s.isNumber()
}

false

every源码:

    public static boolean every(Object self, Closure predicate) {
        return every(InvokerHelper.asIterator(self), predicate);
    }

    public static <T> boolean every(Iterator<T> self, @ClosureParams(FirstGenericType.class) Closure predicate) {
        BooleanClosureWrapper bcw = new BooleanClosureWrapper(predicate);

        do {
            if (!self.hasNext()) {
                return true;
            }
        } while(bcw.call(new Object[]{self.next()}));

        return false;
    }

def list2 =  str.collect{
    String s -> s.toUpperCase()
}
print list2.toListString()

[T, H, E, , 2, , A, N, D, , 3, , I, S, , 5]

与数据结构结合使用

与文件结合使用

闭包关键变量

this
owner
delegate

指向最近封闭类对象

//闭包的三个重要变量:this owner delegate
def scriptClouser = {
    println "scriptClouser this:" + this// 闭包定义处的类
    println "scriptClouser this:" + owner // 闭包定义处的类或者对象
    println "scriptClouser this:" + delegate // 任意对象,默认与owner一致
}
scriptClouser.call()

scriptClouser this:variable.clouserstudy@306e95ec
scriptClouser this:variable.clouserstudy@306e95ec
scriptClouser this:variable.clouserstudy@306e95ec


//定义一个内部类
class Person{
    //静态类型的闭包
    def static classClouser = {
        println "classClouser this:" + this// 闭包定义处的类
        println "classClouser this:" + owner // 闭包定义处的类或者对象
        println "classClouser this:" + delegate // 任意对象,默认与owner一致
    }
    def static say(){
        def classClouser = {
            println "methodClassClouser this:" + this// 闭包定义处的类
            println "methodClassClouser this:" + owner // 闭包定义处的类或者对象
            println "methodClassClouser this:" + delegate // 任意对象,默认与owner一致
        }
        classClouser.call()
    }
}
Person.classClouser.call()
Person.say()

classClouser this:class variable.Person
classClouser this:class variable.Person
classClouser this:class variable.Person
methodClassClouser this:class variable.Person
methodClassClouser this:class variable.Person
methodClassClouser this:class variable.Person


//闭包中定义一个闭包
def nestClouser = {
    def innerClouser = {
        println "innerClouser this:" + this
        println "innerClouser this:" + owner
        println "innerClouser this:" + delegate
    }
    innerClouser.call()
}
nestClouser.call()
innerClouser this:variable.clouserstudy@52af26ee
innerClouser this:variable.clouserstudy$_run_closure1@342c38f8
innerClouser this:variable.clouserstudy$_run_closure1@342c38f8

this指向闭包所在类,owner、delegate指向最近闭包对象


Person p = new Person()
def nestClouser = {
    def innerClouser = {
        println "innerClouser this:" + this
        println "innerClouser this:" + owner
        println "innerClouser this:" + delegate
    }
    innerClouser.delegate = p//修改默认的delegate
    innerClouser.call()
}
nestClouser.call()
innerClouser this:variable.clouserstudy@61001b64
innerClouser this:variable.clouserstudy$_run_closure1@55634720
innerClouser this:objectorention.Person@4b0d79fc

闭包的委托策略

class Student{
    String name
    def preety = {
        "My name is ${name}"
    }
    String toString(){
        preety.call()
    }
}
class Teacher{
    String name
}
def stu = new Student(name: 'Sarash')
def tea = new Teacher(name: 'Amanda')
stu.preety.delegate = tea
stu.preety.resolveStrategy = Closure.DELEGATE_FIRST
println stu.toString()

My name is Amanda


数据结构

列表

//def list = new ArrayList() //java的定义方式
def list = [1, 2, 3, 4, 5]
println list.class
println list.size()

class java.util.ArrayList
5


定义数组:

def array = [1, 2, 3, 4, 5] as int[]
int[] array2 = [1, 2, 3, 4, 5]

列表排序

/**
 * 列表的排序
 */
def sortList = [6, -3, 9, 2, -7, 1, 5]
//Comparator mc = { a, b ->
//    a == b ? 0 : Math.abs(a) < Math.abs(b) ? -1 : 1
//}
//Collections.sort(sortList, mc)
sortList.sort { a, b ->
    a == b ? 0 : Math.abs(a) < Math.abs(b) ? -1 : 1
}
println sortList

[1, 2, -3, 5, 6, -7, 9]


字符串排序

def sortStringList = ['abc', 'z', 'Hello', 'groovy', 'java']
sortStringList.sort { it -> return it.size() }
println sortStringList

[z, abc, java, Hello, groovy]


列表的查找

def findList = [-3, 9, 6, 2, -7, 1, 5]
int result = findList.find { return it % 2 == 0 }
println result

6


def findList = [-3, 9, 6, 2, -7, 1, 5]
def result = findList.findAll { return it % 2 != 0 }
println result.toListString()

[-3, 9, -7, 1, 5]


def findList = [-3, 9, 6, 2, -7, 1, 5]
def result = findList.any { return it % 2 != 0 }
println result

true


def findList = [-3, 9, 6, 2, -7, 1, 5]
def result = findList.every { return it % 2 == 0 }
println result

false


def findList = [-3, 9, 6, 2, -7, 1, 5]
println findList.min { return Math.abs(it) }
println findList.max { return Math.abs(it) }
def num = findList.count { return it % 2 == 0 }
println num

1
9
2


映射

//def map = new HashMap()
def colors = [red  : 'ff0000',
              green: '00ff00',
              blue : '0000ff']
//索引方式
println colors['red']
println colors.red

ff0000
ff0000


def colors = [red  : 'ff0000',
              green: '00ff00',
              blue : '0000ff']
//添加元素
colors.yellow = 'ffff00'
println colors.toMapString()

[red:ff0000, green:00ff00, blue:0000ff, yellow:ffff00]


def colors = [red  : 'ff0000',
              green: '00ff00',
              blue : '0000ff']
colors.complex = [a: 1, b: 2]
println colors.toMapString()

[red:ff0000, green:00ff00, blue:0000ff, complex:[a:1, b:2]]


/**
 * Map操作详解
 */
def students = [
        1: [number: '0001', name: 'Bob',
            score : 55, sex: 'male'],
        2: [number: '0002', name: 'Johnny',
            score : 62, sex: 'female'],
        3: [number: '0003', name: 'Claire',
            score : 73, sex: 'female'],
        4: [number: '0004', name: 'Amy',
            score : 66, sex: 'male']
]

//遍历Entry
students.each { def student ->
    println "the key is ${student.key}, " +
            " the value is ${student.value}"
}
//带索引的遍历
students.eachWithIndex { def student, int index ->
    println "index is ${index},the key is ${student.key}, " +
            " the value is ${student.value}"
}
//直接遍历key-value
students.eachWithIndex { key, value, index ->
    println "the index is ${index},the key is ${key}, " +
            " the value is ${value}"
}

the key is 1, the value is [number:0001, name:Bob, score:55, sex:male]
the key is 2, the value is [number:0002, name:Johnny, score:62, sex:female]
the key is 3, the value is [number:0003, name:Claire, score:73, sex:female]
the key is 4, the value is [number:0004, name:Amy, score:66, sex:male]
index is 0,the key is 1, the value is [number:0001, name:Bob, score:55, sex:male]
index is 1,the key is 2, the value is [number:0002, name:Johnny, score:62, sex:female]
index is 2,the key is 3, the value is [number:0003, name:Claire, score:73, sex:female]
index is 3,the key is 4, the value is [number:0004, name:Amy, score:66, sex:male]
the index is 0,the key is 1, the value is [number:0001, name:Bob, score:55, sex:male]
the index is 1,the key is 2, the value is [number:0002, name:Johnny, score:62, sex:female]
the index is 2,the key is 3, the value is [number:0003, name:Claire, score:73, sex:female]
the index is 3,the key is 4, the value is [number:0004, name:Amy, score:66, sex:male]


//Map的查找
def entry = students.find { def student ->
    return student.value.score >= 60
}
println entry

def entrys = students.findAll { def student ->
    return student.value.score >= 60
}
println entrys

2={number=0002, name=Johnny, score=62, sex=female}

[2:[number:0002, name:Johnny, score:62, sex:female], 3:[number:0003, name:Claire, score:73, sex:female], 4:[number:0004, name:Amy, score:66, sex:male]]


def count = students.count { def student ->
    return student.value.score >= 60 &&
            student.value.sex == 'male'
}
println count

1


def names = students.findAll { def student ->
    return student.value.score >= 60
}.collect {
    return it.value.name
}
println names.toListString()

[Johnny, Claire, Amy]


def group = students.groupBy { def student ->
    return student.value.score >= 60 ? '及格' : '不及格'
}
println group.toMapString()

[不及格:[1:[number:0001, name:Bob, score:55, sex:male]], 及格:[2:[number:0002, name:Johnny, score:62, sex:female], 3:[number:0003, name:Claire, score:73, sex:female], 4:[number:0004, name:Amy, score:66, sex:male]]]


/**
 * 排序
 */
def sort = students.sort { def student1, def student2 ->
    Number score1 = student1.value.score
    Number score2 = student2.value.score
    return score1 == score2 ? 0 : score1 < score2 ? -1 : 1
}

println sort.toMapString()

[1:[number:0001, name:Bob, score:55, sex:male], 2:[number:0002, name:Johnny, score:62, sex:female], 4:[number:0004, name:Amy, score:66, sex:male], 3:[number:0003, name:Claire, score:73, sex:female]]


范围

def range = 1..10
println range[0]
println range.contains(10)
println range.from
println range.to

1
true
1
10


//遍历
range.each {
     println it
}

for (i in range) {
      println i
}

def result = getGrade(75)
println result

def getGrade(Number number) {
    def result
    switch (number) {
        case 0..<60:
            result = '不及格'
            break
        case 60..<70:
            result = '及格'
            break
        case 70..<80:
            result = '良好'
            break
        case 80..100:
            result = '优秀'
            break
    }

    return result
}

良好


面向对象

接口

/**
 * 1.groovy中默认都是public
 */
class Person implements Serializable {
    String name
    Integer age
    def increaseAge(Integer years) {
        this.age += years
    }
    /**
     * 一个方法找不到时,调用它代替
     */
    def invokeMethod(String name, Object args) {
        return "the method is ${name}, the params is ${args}"
    }
    def methodMissing(String name, Object args) {
        return "the method ${name} is missing"
    }
}
def person = new Person(name: 'hongxue', age: 26)
println person.name
println person.age

hongxue
26


/**
 * 接口中不许定义非public的方法
 */
interface Action {
    void eat()
    void drink()
    void play()
}
class Cat implements Action{
    @Override
    void eat() {

    }
    @Override
    void drink() {

    }
    @Override
    void play() {

    }
}

trait DefualtAction {
    abstract void eat()
    void play() {
        println ' i can play.'
    }
}
class Dog implements DefualtAction{
    @Override
    void eat() {

    }
}

def dog = new Dog()
dog.play()

i can play.


元编程

方法调用流程
在这里插入图片描述

/**
 * 1.groovy中默认都是public
 */
class Person implements Serializable {
    String name
    Integer age
    def increaseAge(Integer years) {
        this.age += years
    }
    /**
     * 一个方法找不到时,调用它代替
     */
    def invokeMethod(String name, Object args) {
        return "the method is ${name}, the params is ${args}"
    }
    def methodMissing(String name, Object args) {
        return "the method ${name} is missing"
    }
}
println person.cry()

the method cry is missing


//为类动态的添加一个属性
Person.metaClass.sex = 'male'
def person = new Person(name: 'hongxue', age: 26)
println person.sex
person.sex = 'female'
println "the new sex is:" + person.sex

male
the new sex is:female


Person.metaClass.sex = 'male'
//为类动态的添加方法
Person.metaClass.sexUpperCase = { -> sex.toUpperCase() }
def person = new Person(name: 'hongxue', age: 26)
println person.sexUpperCase()

MALE


//为类动态的添加静态方法
Person.metaClass.static.createPerson = {
    String name, int age -> new Person(name: name, age: age)
}
def person3 = Person.createPerson('fuhongxue', 26)
println person3.name + " and " + person3.age

fuhongxue and 26



http://www.niftyadmin.cn/n/1838380.html

相关文章

双目视觉---立体匹配介绍

原文&#xff1a;http://blog.csdn.net/mysniper11/article/details/8618245 一、概念 立体匹配算法主要是通过建立一个能量代价函数&#xff0c;通过此能量代价函数最小化来估计像素点视差值。立体匹配算法的实质就是一个最优化求解问题&#xff0c;通过建立合理的能量函数&am…

大文件上传的HttpModule实现。(一)

由于网站的升级&#xff0c; 为了解决大文件上传的问题。虽然网站上暂时没有用到&#xff0c;不过自己先记录下来&#xff0c;说不定日后有用呢。 一&#xff1a;原理介绍&#xff0c;NET大文件上传知识整理http://study.pay500.com/4/s43100.htm 二&#xff1a;上传数据分析。…

[摘]将“相关值”导致的Nested Loop优化成Hash Join

原文地址&#xff1a;http://www.itpub.net/thread-1376537-1-2.html “相关值”是我剽窃的一个词&#xff0c;与之相反的是“不相关值”&#xff0c;我借用来描述以下这种情况&#xff1a;在SQL中有两个表A和B要join&#xff0c;join条件是A.nameB.first_name&#xff0c;判定…

MonoRail学习笔记十六:AJax在MonoRail中的使用

AJax几乎成了web2.0的一个代表&#xff0c;Java和Asp.net中都提供了一些AJax操作的控件。在MonoRail中也同样提供了AJax操作的共通类&#xff1a;AJaxHelperAJaxHelper可以指定当文本框输入变化时调用后台代码、可以监控一个Form&#xff0c;当Form内控件值变化时调用后台代码、…

MATLAB---matlab 中的bwlabel函数

用法&#xff1a;L bwlabel(BW,n)返回一个和BW大小相同的L矩阵&#xff0c;包含了标记了BW中每个连通区域的类别标签&#xff0c;这些标签的值为1、2、num&#xff08;连通区域的个数&#xff09;。n的值为4或8&#xff0c;表示是按4连通寻找区域&#xff0c;还是8连通寻找&am…

大马哈鱼的C#学习笔记(2):delegate和event

1.声明delegate&#xff1a; public delegate int myDelegate(string str); 以上语句声明了一个委托&#xff0c;它可以代表返回值为int&#xff0c;参数为string的任何方法&#xff08;static或者实例方法均可&#xff09;。 实际上以上语句会被展开为形如&#xff1a; sealed…

微内核过程引擎的设计思路和构架

阅读完本篇之后&#xff0c;再阅读我不久之前写的《揭秘jbpm流程引擎内核设计思想及构架》&#xff0c;可能更容易理解本文的一些主旨。也建议大家参考我几年前写的《工作流模型分析》、《工作流授权控制模型》、《工作流组织模型》、《工作流引擎调度算法与PetriNet》、《微内…

双目视觉---图像匹配基本算法总结

为了以后查找方便&#xff0c;就先存下来吧&#xff01;&#xff08;原文&#xff1a;http://blog.csdn.net/hujingshuang/article/details/47759579&#xff09; 简介&#xff1a; 本文主要介绍几种基于灰度的图像匹配算法&#xff1a;平均绝对差算法&#xff08;MAD&#xf…