1
头图

A First Look at Groovy

Introduction

Groovy is a JVM language, so as long as there is a JVM it can be executed. Moreover, Groovy and Java can call each other, and the test is silky.

How smooth is it? That is, the .java and .groovy files can coexist in the Java project at the same time, and can call each other.

Groovy is a dynamic language and introduces many interesting features. If Java is likened to regular script, Groovy is running script, and the development efficiency is very high. And Groovy JDK contains a lot of utilities for comfortable development.

Target

Groovy is an optionally typed, dynamic language for the Java platform with many features that are inspired by languages ​​like Python, Ruby, and Smalltalk, making them available to Java developers using a Java-like syntax. Unlike other alternative languages, it is designed as a companion , not a replacement for Java.

​ — Groovy In Action (page 44)

Our goal is not to replace Java, but to be Java's partner. Let Groovy handle some complex processes that are handled in Java.

Operation mode

Simply put, there are two ways:

  • compile: compile time to .class file
  • runtime: dynamically executed as a script by GroovyShell

image-20220909084411141.png

After all, it is a dynamic language. For performance reasons, it is recommended to use Java for the core code and the underlying code. For business logic, logic that needs to change rapidly, try Groovy.

IDE support

Since it is a dynamic language, IDE support is extremely important. At present, IDEA supports well, and the groovy plugin has been added to the default configuration.

image-20220909084507221.png

How to build?

Build configuration file configure Evaluate
Gradle .groovy concise Best way to build, but no one uses it
Maven .XML complex Although it is complicated, everyone is using it and is familiar with it. It is recommended to use maven to introduce it .
Ant \ \ eliminated, no discussion

There are various plugins for maven groovy, GMavenPlus is recommended.

Specific configuration method reference: Groovy + Java hybrid programming solution: GMaven Develop Paper

How cool is it?

POGO

In Java projects, pure data classes are called POJOs. POJOs often have to add a bunch of construction methods, getters, and setters. Although they can be generated by IDE or lombok, they are still very verbose.

POGO can be constructed in Groovy,

 class Person {
    String id
    String name
    
    String toString() {
        return "$id,$name"
    }
}

Default construction, Map construction, getter, setter are all default, very concise.

 def person = new Person(id: '67', name: '靓仔')
println person.getName()

In addition, you can also make POGO into an immutable type, even final are saved,

 @Immutable 
class ImmutablePoint {
    double x
    double y
    
    String toString() {
        return "($x,$y)"
    }
}

There are also some practical functions about POGO, you can refer to Chapter 4 of Making Java Groovy .

GString

Similar to Python's f-strings and JS's template strings. The dollar character is used as a variable placeholder in GString. Here's an example from the Groovy In Action article (page 84):

 def me = 'Tarzan' 
def you = 'Jane' 
def line = "me $me - you $you" 
assert line == 'me Tarzan - you Jane' 

def date = new Date(0) 
def out = "Year $date.year Month $date.month Day $date.date" 
assert out == 'Year 70 Month 0 Day 1' 

out = "Date is ${date.toGMTString()} !"             //|#3 Full syntax with 
assert out == 'Date is 1 Jan 1970 00:00:00 GMT !'      //|#3 curly braces 

 //多行 GStrings 
def sql = """ 
 SELECT FROM MyTable 
 WHERE Year = $date.year 
""" 
assert sql == """ 
 SELECT FROM MyTable 
 WHERE Year = 70 
"""

out = "my 0.02$"             //|#5 Literal dollar sign 
assert out == 'my 0.02$'

json

 import groovy.json.JsonSlurper

String url = 'http://api.icndb.com/jokes/random?limitTo=[nerdy]'
String jsonTxt = url.toURL().text
def json = new JsonSlurper().parseText(jsonTxt)
def joke = json?.value?.joke
println joke

Interface call, json parsing in one go. And the value process is very simple: json?.value?.joke , no need for a bunch of if else judgments, and no need for methods such as Optional .

unit test

Groovy makes testing Java much easier

——Making Java Groovy

If you want to use Groovy, but have doubts about applying it to business logic, then writing unit tests is perfect. It will not affect the business code, and you can get started step by step, and unit tests are written concisely.

 class CutoutCustomerIdTagTest {

    @Test
    void cutout() {
        def ctx = new DmContext(uid: '001122')
        def cutId = new CutoutCustomIdTag().doTag(ctx)
        assert cutId == '22'
    }
}
 class PermissionTest {
    @Test
    void check() {
        def permission = new Permission(modify: ['Tom', 'Jerry'])
        assert permission.checkModify('Tom')
        assert permission.checkModify('Jerry')
    }
}

references


骚铭科技
1 声望2 粉丝

条路自己行,扑街唔好喊