发布于 2026-01-06 6 阅读
0

Groovy Java:2019 年使用 Groovy 的 10 个理由 结论 由 Mux 呈现的 DEV 全球展示挑战赛:展示你的项目!

Groovy Java: 2019 年使用 Groovy 的 10 个理由

结论

由 Mux 主办的 DEV 全球展示挑战赛:展示你的项目!

为什么选择 Groovy?

我加入公司DevOps团队大约一年了,我们使用的主要工具之一是Jenkins ,它与Groovy兼容性很好。我主要使用Groovy来编排流水线和自动化一些繁琐的任务。

Groovy 是一种功能强大的 Java 平台语言,它可以与任何 Java 程序无缝集成。它也是一种优秀的脚本语言,语法强大且易于学习。

Groovy旨在通过简洁、熟悉且易于学习的
语法
来提高开发人员的效率。它可以与任何Java程序无缝集成,并立即为您的应用程序提供
强大的功能,包括脚本功能、领域特定语言编写、
运行时和编译时元编程以及函数式编程。

以下是我在过去一年中学到的让我爱上 Groovy 的 10 个特性:

1. 简洁性

我之前在Java后端开发团队工作,所以学习Groovy对我来说轻而易举。它基于Java标准库构建,并提供了许多额外的功能。其中大多数功能都大大简化了编程。

1.1 声明列表/映射

Groovy 是一种可选类型的语言,您可以使用def关键字来声明变量。例如,声明列表或映射非常简单:

def myList = []
def myMap = [:]
Enter fullscreen mode Exit fullscreen mode

1.2 遍历列表/映射

使用闭包遍历它们变得极其简单易读

myList.each {element -> 
    println element
}

myMap.each {entry -> 
    println "User: $entry.user | Email: $entry.email"
}
Enter fullscreen mode Exit fullscreen mode

2. 字符串插值

[字符串] 插值是指在对字符串进行求值后,用字符串的值替换字符串中的占位符。

在 Groovy 中,占位符用点号括起来${}$以点号开头。

前面的代码片段展示了一个字符串插值的例子。下面是另一个例子:

try{
    throw new Exception()
}catch(Exception e){
    println "Error during operation. Cause: ${e}"
}
Enter fullscreen mode Exit fullscreen mode

3. 铸造

Groovy 使用 `--type` 运算符使类型转换变得非常简单易读as。要使用此操作数,被转换的类必须实现 ` asType()--type` 方法。对于列表、枚举器等标准类,这已经是默认实现的。

例如:

enum Employee {
    MIKE,
    HANNA
}

String name = "JOHN"

try{
    name as Employee
}catch(Exception e){
    println "Could not find employee ${name}. Cause: ${e}"
}
Enter fullscreen mode Exit fullscreen mode

4. JSON 转类

我经常使用带有 JSON 响应的 Web 服务,因此不可避免地需要将响应映射到 Groovy 类。Groovy 本身就提供了这个功能,而且非常简单,只需将 JSON 数据传递给类构造函数即可。

String response = '{name:"John", position: "Developer", age: 32}'

// Json response to map
def employeeMap = new JsonSlurper().parseText(response)
// Consider an Employee class with the attributes name, position and age
Employee employee = new Employee(employeeMap)
Enter fullscreen mode Exit fullscreen mode

就这样。我们刚刚根据一个 JSON 字符串构建了一个员工对象。

反过来也一样简单:

def json = JsonOutput.toJson(employee)
// json == '{name:"John", position: "Developer", age: 32}'
Enter fullscreen mode Exit fullscreen mode

5. 断言

Groovy 和 Java 一样有相同的assert语句,但功能更强大——因此得名——强力断言

区别在于断言结果为真时的输出false。例如:

def contacts = ['John', 'Anna']

assert contacts.isEmpty()

//Output:
//ERROR org.codehaus.groovy.runtime.powerassert.PowerAssetionError:
//assert contacts.isEmpty()
//       |        |
//       |        false
//       [John, Anna]
Enter fullscreen mode Exit fullscreen mode

这样你就能很容易地理解是什么导致了论断失败。

6. 定义变量

Groovy 的类型是可选的,这意味着你可以为变量指定类型,或者直接使用关键字 `type` def。声明 List 或 Map 时也一样,它们的类型是可选的。例如:

String name
int age
def address
List friends = ['John', 'Anna']
Map family = ['Mother':'Mary', 'Father':'Joseph']

def getFamilyMember("Mother"){ ... }
Enter fullscreen mode Exit fullscreen mode

对于了解 Javascript 的人来说,这类似于关键字var

这赋予了你极大的灵活性,但使用时务必谨慎。它可能会增加团队成员或其他使用你代码的人阅读代码、理解输入输出预期含义的难度。

7. 哈希

如果你用过 Java,你可能知道对字符串进行哈希处理有多么冗长——除非你使用第三方库。

Groovy 2.5 为类引入了一些实用的方法String。计算哈希值就像调用字符串的方法一样简单。Groovy 让这一切变得如此简单:

def password = "thisIsMyPassword"

def md5 = password.md5()
def sha256 = password.sha256()
//For other algorithms use digest() method
def sha1 = password.digest('SHA-1')
...
Enter fullscreen mode Exit fullscreen mode

8. 操作员

Groovy 支持其他语言中最常用的运算符。但这还不够,Groovy 还提供了一些更有趣的运算符。以下列举几个:

猫王操作员

这是三元运算符的简化版本。例如,当条件可能为空时,这非常有用。

// Instead of this
def user = person.name ? person.name : 'Guest'
// Use this
def user = person.name ?: 'Guest'
Enter fullscreen mode Exit fullscreen mode

安全导航操作员

另一个可以用来检查变量是否为空的运算符是安全导航运算符。

def user = person?.name
// user == null
Enter fullscreen mode Exit fullscreen mode

当您想要避免NullPointerException抛出异常时,请使用此运算符。如果您要访问的对象为 null,此运算符将返回一个空值,null而不是抛出一个异常NullPointerException

价差操作商

展开运算符 ( .*) 用于对集合中的所有项执行操作,而不是像之前那样使用循环或闭包。例如:

def numbers = [1,2,3,4,5,6]
*numbers // == [1,2,3,4,5,6]

def people = [
    new Person(name: 'John', age: '25'),
    new Person(name: 'Anna', age: '21')
]

def friends = people*.name // friends = ['John', 'Anna']
Enter fullscreen mode Exit fullscreen mode

9. 特征

特征是语言的一种结构性构造,它允许:

  • 行为构成

  • 接口的运行时实现

  • 行为覆盖

  • 与静态类型检查/编译的兼容性

我喜欢把特性(trait)看作是接口,你可以在其中实现方法。当你有一个非常复杂且结构化的应用程序,并且想要保持代码的清晰性时,特性非常有用。

这绝对是我在早期 Java 版本中缺失的东西。

举个例子:

trait Sociable {
    void greet() { println "Hello!" }
}

class Person implements Sociable {}

Person p = new Person()
p.greet() // Hello!
Enter fullscreen mode Exit fullscreen mode

10. 正则表达式

Groovy 原生支持正则表达式,而且非常简单。它有 3 个正则表达式运算符:

  • ~这是模式运算符,它是创建实例的简单方法java.util.regex.Pattern
def pattern = ~"^abc{2}\d"
// pattern instanceof Pattern == true
Enter fullscreen mode Exit fullscreen mode
  • =~这是查找运算符,它会在字符串中查找模式并返回一个结果Matcher
def pattern = ~"abc{2}\d"
def found = "abcc5" =~ pattern
// found instanceof Matcher == true
Enter fullscreen mode Exit fullscreen mode
  • 最后是匹配运算符 ==~,它返回true字符串是否与正则表达式严格匹配:
def found = "abcc5" ==~ pattern
// found == true
Enter fullscreen mode Exit fullscreen mode

结论

如果你多年来一直使用 Java 或其他面向对象编程语言进行编程,那么 Groovy 会让你感觉耳目一新。

它让事情变得更加轻松简单,也更加简洁。此外,脚本和领域特定语言等额外功能,将 Groovy 提升到了一个新的水平,赋予了它一种老旧语言所缺乏的全新面貌。

希望这篇文章对您有所帮助。如果您有使用 Groovy 的经验,或者想分享您的使用方法,欢迎在下方评论区留言。:)

文章来源:https://dev.to/jcoelho/10-reasons-to-use-groovy-in-2019-431f