Understand Groovy in seconds [only for Java developers]

0 Preface

Recently, I found that the test students were using groovy. I was curious and took a look. After learning about it, I found that groovy can be used in Java projects, and there is no need to worry about compatibility issues.

The operating principle of the upstream assembly program of the JVM is as follows: Any language, anyway, the JVM only recognizes bytecode files, as long as your program can be compiled into a bytecode file that the JVM recognizes.
insert image description here


Later, when writing some Java programs, I plan to introduce groovy appropriately. Anyway, the two are compatible, and using groovy can save a lot of code.


1 Grammatical features

1.0 output

Java console output syntax: System.out.println()
Groovy console output syntax: println()

1.2 Statement

Java needs to add a semicolon ";" after the end of the line of code, or after the end of each sentence. But Groovy doesn't need it, you can add it or not, and Groovy will infer whether the statement ends by itself.

// Java 表达方式
public int a = 1;
// groovy 表达方式,两种都支持,会自行推断
public int a = 1
public int a = 1;

1.3 Operators

All Java operation symbols are supported by groovy, such as addition and other operations += and the like.
Groovy has expanded on the operators supported by the original Java, providing a feature that I especially want to see in Java, scope.
The range of groovy is represented by two points, for example: 1…10, which means an integer number from 1 to 10, including 1 and 10.
At the same time, the range operator can be used with the in keyword, such as boolean a = 1 in 1…10 // true

def ints = 1..10
println ints // 输出:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
println 5 in ints // 输出:true

1.4 Define variables & methods

Groovy supports all method definitions supported by Java. However, the partial syntax has been optimized to make groovy more open. If you don't know or are not sure about the return type of the method, you can use def instead of the return type to define the method. [Tip: Groovy has also extended the object property, but I think it is better to use less of this thing. If readers want to know more about this aspect, please go to Baidu.

// java 方式
//  变量
String s1 = "123";

// 方法
public String fun1(String r1){
    
    
	...
}
// groovy 方式,以下两种方式都支持,def 代表定义的意思,至于方法返回什么类型,Groovy解释器会对其进行类型推断。
// 变量
def s1 = "123"
String s1 = "123"
// 方法
String fun1(String r1){
    
    
	...
}
def fun1(String r1){
    
    
	...
}

Class 1.5

For Java, all POJO attributes default to **"default type"**, which can only be seen in the same package. Most Java developers will add a private modifier to POJO properties, indicating that the property can only be accessed in this way. But for groovy developers, there is no need to add a private modifier, because its properties are modified with private by default.


Tip : Kotlin has an interesting feature, that is, class properties can be marked with set and get, which is equivalent to the getter and setter methods in Java POJO.

1.6 NPE judgment

Java hates NPE, and Java workers have come up with various methods, such as Objects.requireNonNull(obj), and groovy can use the question mark "❓" to solve this problem. as follows:

// java 方式
Objects.requireNonNull(obj)
// groovy 可以用问号代替 NPE 判断
obj?.find {
    
    }

1.7 Template Strings

 def name = "Groovy"
 def temp = "This is ${name}"
 // 使用方式就是 ${var}
 println temp // This is Groovy
 // 还可以做表达式
 def temp2 = "This Tutorial is about ${name + "123"}"
 println temp // This is Groovy123

2 collection features

2.0 List of definitions

Java usually needs to use new ArrayList<>() to define lists, and groovy defines lists is very fun. Specifically look at the code:

// 定义列表,java 可以这样定义 Lists.of(1,2,3,4)
def ints = [1,2,3,4]
// 添加元素,Java 可以这样添加 ints.add(5)
ints.add(5)
ints << 5 // 骚吧,好玩吧
// 删除元素,Java 这样 ints.remove(4)
ints.remove(2)
// 读取元素,ints.get(2)
ints.get(3)
ints[3] // 读取最后一个元素的骚操作:ints[-1]
// 拼接元素, Java 这样 ints.addAll(list)
def list = [5,6,7]
ints += list
ints << list
// 去除元素,Java 这样 ints.munit(list)
def list = [1,2]
ints -= list
// 遍历列表,Java 这样 ints.foeEach(item -> {}) 或者 for-in
for(def i in ints) {
    
    ...}
ints.each({
    
    it -> ...}) //这是闭包,后面会讲
// 查元素,Java 这样 ints.stream().find(Option)
ints.find({
    
    it -> ...}) // 返回第一个发现的元素
ints.findAll({
    
    it -> ...}) // 返回所有符合条件的元素
// 其它
ints.join(",")// 用特殊字符串拼接列表,输出 "1,2,3,4"
ints.count(4)// 计数,输出1
ints.sort() // 排序,输出[1,2,3,4]

3 Mapping properties

You can use new HashMap<String, String>() to define mapping in Java, and it is very simple to define mapping in Groovy, as follows:

 def map = [
     "k1": "v1",
     "k2": "v2",
     "k3": "v3"
 ]
 println map // [k1:v1, k2:v2, k3:v3]
 map."k4" = "v4" // 知道名字的
 def k4 = "k4"
 map[k4] = "v4" // 不知道名字的
 println map // [k1:v1, k2:v2, k3:v3, k4:v4]

Tip: Both supported by Java and supported by groovy

4 closures

Closures in groovy are equivalent to lambdas in Java, but there are differences in writing, as follows:

// java 的 lambda 
(args...) -> {
    
    }
// groovy 中的 Closure(闭包)
{
    
     args -> }

Both are written under curly braces. Java parameters need to be wrapped in parentheses (one parameter can be omitted), and the execution body is wrapped in curly braces. But if it is groovy, its closures are all in curly braces. For a parameter, groovy can omit it and directly use the it keyword to replace the default parameter. as follows:

// java 的 lambda 对 for-each 支持
List<String> list = ["1234","1245","23446"]
// Java 
list.forEach(item -> {
    
    
	System.out.println(item);
})
// groovy
list.forEach({
    
     item ->
	System.out.println(item);
})
list.forEach({
    
    
	System.out.println(it); // it 为默认参数,等价于item
})

Well, just know how to use it, and Baidu will write the redundant ones!


Extra Story 1: Mixed development of Java and groovy [maven project]

step1: Add groovy dependency

<!-- groovy 支持 -->
<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy</artifactId>
</dependency>

tip: There is no need to specify the version information. Some source codes in spring boot are also developed with groovy, which itself has a parent set of groovy.

step2: Add groovy compilation plugin

<plugin>
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.13.1</version>
    <executions>
        <execution>
            <goals>
                <goal>addSources</goal>
                <goal>addTestSources</goal>
                <goal>generateStubs</goal>
                <goal>compile</goal>
                <goal>generateTestStubs</goal>
                <goal>compileTests</goal>
                <goal>removeStubs</goal>
                <goal>removeTestStubs</goal>
            </goals>
        </execution>
    </executions>
</plugin>

tip: The groovy compilation plugin will be bound to the life cycle of maven, and the groovy plugin scans not the source code in the Java directory, but the source code in groovy

step3: Create a source code directory at the same level as Java

insert image description here
tip1: If it is spring boot development, the groovy package should be lower than the package level of the startup program (the class containing the main method).
insert image description here

Guess you like

Origin blog.csdn.net/qq_44503987/article/details/126455294