Groovy Series 1 Groovy Basic Grammar

Table of contents

Why learn Groovy

Introduction to Groovy

Groovy Features

Groovy in action

dynamic type

Simple and clear list, map type

Everything in the groovy world is an object

Attribute manipulation just got easier

GString

Closure

Delegation: delegate

Switch just got simpler

metaprogramming

mandatory type checking

Elvis Operator

secure access


Why learn Groovy

        As a Java-based programmer, Groovy has a unique advantage in compatibility as a scripting language (dynamic language) on the Java platform. Students who have been in contact with Aandroid development have already come into contact with the Gradle construction project (Gradle construction also supports the construction of Java projects). Gradle is a framework for building projects implemented using Groovy. In addition, the new version of idea recommends using Gradle for plug-in development. Of course, the above is just an objective explanation of the development trend of Groovy technology (including but not limited to these aspects) to illustrate that we need to learn, from our own level, learn more and benefit more, or students who have technical pursuits or technical ideals, learn more Door technology is also an improvement for oneself. Next, let us walk into the world of Groovy together.

Introduction to Groovy

        Apache Groovy is a powerful, optionally typed and dynamic language with static typing and static compilation for the Java platform, designed to increase developer productivity through a concise, familiar, and easy-to-learn syntax. It integrates smoothly with any Java program and immediately provides your application with powerful features, including scripting capabilities, domain-specific language authoring, runtime and compile-time metaprogramming, and functional programming.

                                                                                                                           -- groovy official website

        The above is the official website introduction. My personal popular understanding is as follows. Groovy is an agile dynamic language for the Java virtual machine, a mature object-oriented programming language, and a pure scripting language. Groovy runs on the JVM environment, and has both the characteristics of java language and scripting language in syntax, which greatly simplifies the syntax. At the same time, it has closures and other features in dynamic languages, which make up for the dynamism that pure Java code does not have. We can modify the code logic arbitrarily while the program is running without re-publishing.

        Groovy 1.0 was released on January 2, 2007. Groovy is released under the Apache License v 2.0. The official site for Groovy is The Apache Groovy programming language

Groovy Features

        Groovy has the following features (official website API documentation: The Apache Groovy programming language - Groovy Development Kit ):

  1. Groovy is an object-oriented scripting language based on the Java virtual machine and supports both static and dynamic typing.
  2. Groovy is easy for Java developers because the syntax of Java and Groovy is very similar and existing Java libraries can be used.
  3. Operator overloading is supported.
  4. Native syntax lists and associative arrays.
  5. Native support for regular expressions.
  6. Various markup languages ​​such as XML and HTML are natively supported.
  7. Groovy extends java.lang.Object.

Groovy in action

dynamic type

        The first feature of groovy is the dynamic feature. After defining a variable, you can assign any type of value to the variable; groovy provides this support method, but for good coding habits, we are to put an end to this development method of.

def v = 0;//定义了数值类型的变量v 
v = new Date();//然后又给它赋与Date类型的值. 
println(v);

Simple and clear list, map type

        We can use groovy to define list and map data structures simply and clearly. Unlike in Java China where we have to define a type before assigning a value, Groovy can directly use syntactic sugar to quickly assign a value. See the following code examples for details. Only typical APIs are listed for concept illustration. If you are interested in the remaining APIs, you can try and practice by yourself.

  • Use "[]" to define the list list and directly operate on it
// list 可以看到的是编译器帮我们作何类型识别
def list = [1, 2]
// 这个是groovy的list的API从左边插入一个记录
list.leftShift(3)
// push是从插入到列表前面
list.push(0)
// add和我们java的List一样是追加到最后
list.add("abc")
// groovy中的<<可以对list数据类型的作用添加值,也是追加到最后面,需要注意的是在数字类型时是位运算操作
list << "<<号";
// "+"在groovy的语法中也是追加元素到集合中,并且是追加到最后
list += "加上+="

// 查看打印结果可以看到我在每个API的功能描述上的说明
// [0, 1, 2, 3, abc, <<号, 加上+=]
println(list)

// 也可以采用 lambda 表达式遍历集合
list.forEach({ println(it)})
  • Use ":" to separate the key and value to define the map data, the key does not need to be enclosed in quotation marks, and the key can be used to directly read and write to the map
def map = [a: 2, b: new Date()];

// 写入 直接追加到map集合中
map.put("aaaa","bbb")

println(map)
// 写入 直接采用Map的key进行操作
map.a = "a value change"

println(map)

// 结果如下 可以看到 key 为 "a" 的value被改变
[a:2, b:Sun May 28 11:19:56 CST 2023, aaaa:bbb]
[a:a value change, b:Sun May 28 11:19:56 CST 2023, aaaa:bbb]

Everything in the groovy world is an object

        How to understand the above concepts? Compared with the Java language, we all know that in the Java language, basic types and reference types are treated differently. Primitive types have no method calls because primitive types are accessed by value, and Groovy is more of an object-oriented language than Java in this respect.

// 在groovy中,一切都是对象。一切都可以当成对象来使用;
// 即使在Java中的基本类型也更像是一个对象
100.times {println("hello world")}

Attribute manipulation just got easier

        Unlike in Java, to operate the properties of an object, you must use the get and set methods, even if the properties are defined as private. In groovy, to define a javabean, it is no longer necessary to write getter and setter methods. You can directly use the "." to operate the read and write attributes.

class JavaBeans {
    String a
    // 即使是定义成private 也可以直接访问
    //    private String a
}

def beans = new JavaBeans();

beans.a = "object set property value"

println(beans.a)

GString

        GString is a tool provided by Groovy for fast processing of strings. The string under double quotes "" can directly embed variables in a simple and clear way through $var or ${var}. And GStrng will call the closure that contains it, and GString without parameters will call the closure and print the result we expect to Writer.

// case1
def a = "a"
def b = "b"
// a=a,b=b 快速替换字符串变量
println("a=${a},b=$b")

// case2
def name = 'lly'
def hello = "hello $name !"
// 结果:hello lly ! 快速替换字符串变量
println hello
// 注意这一行
name = '阳仔'
// 结果:hello lly !
println hello

// case3 :GStrng会调用包含的闭包 无参GString会调用闭包并打印我们期待的结果到Writer
def quote = "${-> name} , welcome"
// 结果:阳仔 , welcome
println quote
// 注意这一行
name = 'lisi'
// 结果:lisi , welcome
println quote

Closure

        A closure in groovy can be seen as a code block, which can have no parameters and return values; it is like the lambda syntax above java8 or like a java inner class with one method (here is similar to the functional programming specification definition). Implicit built-in variables in groovy closures, through which variables we can do things to get individual element operations. Such as iteration, judgment and other businesses.

it: When no parameters are defined in the closure method, the it variable can also be used directly;

this: Same as this in java;

owner: basically the same as this, except that in one case, if the closure is defined in another closure, the owner points to the closure object that defines it.

// 闭包中内置了很多迭代方法,如find、findAll、collect等等。这里需要注意的是内置对象 it 的使用
def list = ['foo', 'bar']
def newList = []
list.collect(newList) {
    it.toUpperCase()
}
// 结果:[FOO, BAR]
println newList

//或者
list = ['foo', 'bar']
newList = []
list.collect(newList, {
    it.toUpperCase()
});
// 结果:[FOO, BAR]
println newList


// 在groovy闭包中的隐含内置变量

def a = {
    println "a this:" + this
    println "a owner:" + owner // ower指向b

    def b = {
        println "b this:" + this
        println "b owner:" + owner // ower指向b
    }
    b.call()

}
a.call()

// 结果:这里可以看到 this 和 owner 异同
a this:script.GroovyDemo1@78b236a0
a owner:script.GroovyDemo1@78b236a0
b this:script.GroovyDemo1@78b236a0
b owner:script.GroovyDemo1$_run_closure3@304b9f1a

Delegation: delegate

        The delegate in Groovy is basically the same as the owner, except that it delegates to the new object via Closure.setDelegate().

def scriptClosure = {
    println "scriptClosure this:" + this
    println "scriptClosure owner:" + owner
    println "scriptClosure delegate:" + delegate
}
println "before setDelegate()"
scriptClosure.call()
scriptClosure.setDelegate("lly")
println "after setDelegate()"
scriptClosure.call()

// 结果:
scriptClosure this:script.GroovyDemo1@5c371e13
scriptClosure owner:script.GroovyDemo1@5c371e13
scriptClosure delegate:script.GroovyDemo1@5c371e13
after setDelegate()
scriptClosure this:script.GroovyDemo1@5c371e13
scriptClosure owner:script.GroovyDemo1@5c371e13
scriptClosure delegate:lly

Switch just got simpler

        The switch in Groovy can allow expressions such as lists, objects, ranges, etc. to be used as case basis

def x = 20;
switch (x) {
    case [1, 2, 3, 4, 5]:
        println("aaaaaa")
        break;
    case "foo":
        println("bbbbb")
    case 10..1000:
        println("ccccc")
        break;
    case Date:
        println("dddddd")
        break;
}

// 结果: 因为 20 在 10到1000 的范围内
ccccc

metaprogramming

        In Groovy, you can use the metaClass class to add properties and methods to meta objects. The reason is that in Groovy, if your object uses a method that it has not defined, it will not report an error, at least it will not report an error when compiling. This is because of Groovy's special runtime mechanism. When you call a method of an object, he will first check whether the property and method are defined in the class. If not, you will go to MeteClass to find it. In Java, all classes will integrate Object, while in Groovy, all classes will inherit GroovyObject, and this class has a method to obtain MeteClass. In this way, you can dynamically add properties and methods to objects during operation, even static methods. If this method is not defined in MeteClass, it is necessary to find out whether the methodMissing and invokeMethod methods are implemented in the entity class in turn, and special processing can be done in these two methods.

// 基本元编程
// 对String类,添加一个uppers方法
String.metaClass.uppers = { -> toUpperCase() };
println "aaa".uppers()
//结果:AAA

// 对Interger类,添加一个say方法
Integer.metaClass.say = { -> "I am Interger" }
def i = new Integer(100);
println i.say()
// 结果:I am Interger

// 给对象添加属性、方法、静态方法
class Person {
    String name;
    Integer age;

    String eat() {
        println(name + "like eat")
    }
}
def p = new Person(name: "阳仔", age: 18)
p.eat()

// 给对象添加属性
p.metaClass.sex = '男'
// 给对象添加方法
p.metaClass.drink = {
    -> println "喜欢喝饮料"
}
// 给对象添加静态方法
p.metaClass.static.play = {
    -> println "喜欢玩游戏"
}

println "${p.name},今年${p.age}岁了,性別是${p.sex}"
p.drink()
p.play()

// 结果
阳仔like eat
阳仔,今年18岁了,性別是男
喜欢喝饮料
喜欢玩游戏

mandatory type checking

        In our previous learning process, we found that Groovy is a weak type check. Whether it is a variable or a collection, it can receive any type of data. If we want to restrict a certain type in some scenarios, we must use the @TypeChecked annotation Have fun enforcing type checking. In the closure, if you need strong type checking, you can define the parameter type like java syntax.

class Foos{
    int  i = 42.0; //编译通过
}

@TypeChecked
class Foo{
    int  i = 42.0; //编译不通过
}

//在闭包中,如果需要强类型检查,可以像java语法一样定义参数类型
def list = ["a","b","c"]
// 编译不通过
//def list = ["a","b","c", 1]
list.collect {
    String it -> it.toUpperCase()
}
println(list)

Elvis Operator

        Groovy adopts Elvis Operator operation to further simplify the ternary operator.

def a = null;
// 在定义b变量时,先判断a是否有值,如果有,就取a的值作为b的值,否则就取值"b"
def b = a ?: "b"; 
println(b)

secure access

        It is the same as the empty judgment in our Java, but it is more concise.

def person;
//先判断person是否为不为null,然后,再调用getName方法
String name = person?.getName();
println(name)

Guess you like

Origin blog.csdn.net/lly576403061/article/details/130913526