首页 >Java >java教程 >Groovy 相对于 Java 的特性和优势

Groovy 相对于 Java 的特性和优势

DDD
DDD原创
2024-09-18 14:32:06545浏览

Features and Advantages of Groovy Over Java

Groovy 是一种为 JVM 构建的动态语言。它与 Java 代码和库无缝集成,以 Java 的优势为基础,同时添加受 Python 和 Ruby 等语言启发的功能。
与 C、C 或 Python 等独立编程语言不同,Groovy 依赖于 Java。 Java 中引入的新特性也被 Groovy 所采用。 Groovy 的主要目标是减少重复任务和样板代码,使其成为在 JVM 上编写脚本的绝佳选择。

Java 之间的差异

Java 以其强大的功能而闻名,通常被认为是一种复杂且重量级的编程语言。相比之下,Groovy 提供了一种更简化的 Java 开发方法。作为一种基于 JVM 的语言,具有静态和动态类型功能,Groovy 简化了编码的许多方面。

Java 开发人员通常会发现 Groovy 很容易上手,使他们能够快速增强自己的技能并扩展 Java 的功能。 Groovy 的一个显着优势是其在简化单元测试方面的声誉。

考虑下面的程序,让我们解释一下 Java 和 Groovy 的输出差异。

int method(String arg) {
    return 1;
}
int method(Object arg) {
    return 2;
}
Object o = "Object"; 
int result = method(o);

上述方法在 Java 和 Groovy 中给出了不同的输出。

输出

Java 输出:2
Groovy 输出:1

发生这种情况是因为,
在 Java 中,方法重载是在编译时根据参数的编译时类型来解决的。
然而,在 groovy 方法中解析发生在运行时。

Java 和 Groovy 之间的其他显着差异是,

默认导入:
Groovy 为常用包提供了一组默认导入,可以简化代码并减少显式导入语句的需要。例如,Groovy 自动从 java.util、java.io 和 groovy.lang 等包中导入类。相比之下,Java 要求显式指定所有必要的导入。

闭包

闭包是独立的代码块,可以接受参数并执行代码。它们可以编写一次并在以后使用。与标准方法或函数不同,闭包可以捕获并使用周围上下文中的变量。虽然从技术上讲,对象和闭包之间没有太大区别,但闭包显着提高了代码的可读性和灵活性。

调用闭包

在常规闭包中可以通过两种方式调用。

  • 可以像常规函数一样调用。
  • 使用 Closure 的 .call() 方法。
def sumTwoNums = {
    a,b -> 
    println "Adding ${a} and ${b}"
    return a+b
}

println sumTwoNums(2,4)
println sumTwoNums.call(5,2)

输出

6

def updateCounter = {
    def counter = 0
    return {
        return counter = counter + 1;
    }
}

def updateCounterFunc = updateCounter.call()

println updateCounterFunc()
println updateCounterFunc()

输出

1
2

在上面的程序中,updateCounter定义了一个局部变量counter并返回另一个闭包。由于闭包捕获其周围上下文的方式,返回的闭包可以访问计数器变量,这将在本博客后面进行解释。

当执行 updateCounter.call() 时,它将 counter 初始化为 0 并返回一个新的闭包,每次调用它时 counter 都会加 1。

闭包的特点

为了完全理解 groovy 中的闭包,我们需要了解 this 是什么以及闭包的所有者。

在groovy中,该关键字指的是封闭类。例如,如果我们在 User 类中存在的闭包中访问 this,那么 this 将引用 User 类。

如果我们在一个嵌套在另一个闭包中的闭包中使用 this,并且这两个闭包都存在于一个类中,那么 this 指的是最近的外部类。

所有者

闭包的所有者与此类似,但owner关键字指的是闭包的封闭对象或闭包。

让我们看一个例子来清楚地理解闭包的所有者和 this。

class Example{
    def outerClosure = {
        def innerClosure = {
            println "Inner closure ---> $this"
        }
        innerClosure()
        println "Outer closure ---> $this"
    }

    def printCurrentObject(){
        println "Current object ---> $this"
    }
}

Example example = new Example()

example.outerClosure.call()

example.printCurrentObject()

输出

内部封闭--->示例@6e57e95e
外封口 --->示例@6e57e95e
当前对象--->示例@6e57e95e

在上面声明的嵌套闭包中,即使涉及到多层闭包,当前对象(this)的引用仍然指向外部类实例。这允许从任何嵌套闭包中访问封闭类的属性和方法。

class Example{
    def outerClosure = {
        def innerClosure = {
            println "Inner closure owner ---> " + getOwner()
        }
        innerClosure()
        println "Outer closure owner ---> " + getOwner()
    }

    def printThis(){
        println "Current object ---> $this"
    }
}

Example example = new Example()

example.outerClosure.call()

example.printThis()

输出

内封闭所有者 --->示例$_closure1@410954b
外封拥有者--->示例@46cc127b
当前对象--->示例@46cc127b

Inner Closure Owner:
The innerClosure is enclosed within the outerClosure, so getOwner() in the innerClosure returns the outerClosure.

Outer Closure Owner:
The outerClosure itself is enclosed within the instance of the Example class. Therefore, getOwner() in the outerClosure returns the Example class instance

Delegation

In Groovy, delegation is a mechanism that allows an object to pass on method calls to another object (known as the delegate). This concept is particularly useful when working with closures. Groovy provides the delegate property in closures to allow you to specify another object that will handle method calls not defined within the closure.

The below is an example of how delegation works in groovy

class ServiceLogger{
    def log(message){
        println "Service: $message"
    }
}

class DatabaseLogger{
    def log(message){
        println "Database: $message"
    }
}

def logMessage = {
    log(it)
}

logMessage.delegate = new ServiceLogger()     -> 1

logMessage("User created successfully")

logMessage.delegate = new DatabaseLogger()

logMessage("User fetched from DB successfully")

Output

Service: User created successfully
Database: User fetched from DB successfully

In the above example, there are two classes ServiceLogger and DatabaseLogger and a closure named logMessage.

First we are assigning the ServiceLogger as a delegate for the closure. So when the closure logMessage is called then the delegate's (log) function is invoked. Later when we change the delegate of the closure to DatabaseLogger the log method present inside the DatabaseLogger is invoked.

Let's see another example to understand delegation in detail.

class MediaPlayer{
    def fileName
    def play = { "Playing ${fileName}" }
}

class VideoPlayer{
    def fileName
}

MediaPlayer mediaPlayer = new MediaPlayer(fileName:"theme-music.mp3")
VideoPlayer videoPlayer = new VideoPlayer(fileName:"trailer.mp4")

println mediaPlayer.play()

mediaPlayer.play.delegate = videoPlayer

println mediaPlayer.play()

Initially, when mediaPlayer.play() is called, it uses the fileNamefrom the MediaPlayer instance, resulting in the output: Playing theme-music.mp3. Even after changing the delegate of the closure to VideoPlayer, the play closure still prints the MediaPlayer file name. This behaviour is due to the default delegation strategy in Groovy closures. To understand this, let's explore the different delegation strategies in Groovy closures.

Delegation Strategy

In Groovy, the delegation strategy defines how a closure resolves method calls or property references that are not explicitly defined within the closure itself.

Groovy provides several delegation strategies that dictate how a closure resolves calls to methods or properties:

Closure.OWNER_FIRST (default): The closure first tries to resolve the call in the owner, then the delegate.
Closure.DELEGATE_FIRST: The closure first looks for the method/property in the delegate, and if not found, it checks in the owner.
Closure.OWNER_ONLY: The closure only looks for method/property in the owner and ignores the delegate.
Closure.DELEGATE_ONLY: The closure only resolves method/property in the delegate and ignores the owner.

So in the above program though we have changed the delegate of the closure while executing the closure will use its owner's methods or properties. Here the owner of the closure play is MediaPlayer.

class MediaPlayer{
    def fileName
    def play = { "Playing ${fileName}" }
}

class VideoPlayer{
    def fileName
}

MediaPlayer mediaPlayer = new MediaPlayer(fileName:"theme-music.mp3")
VideoPlayer videoPlayer = new VideoPlayer(fileName:"trailer.mp4")

println mediaPlayer.play()

mediaPlayer.play.resolveStrategy = Closure.DELEGATE_FIRST
mediaPlayer.play.delegate = videoPlayer

println mediaPlayer.play()

Output

Playing theme-music.mp3
Playing trailer.mp4

Here we have changed the resolution strategy of the closure to DELEGATE_FIRST, now the closure uses the delegate's methods and properties.

Another advantage of using Closures is lazy evaluation of strings. Here is an example

def name = "Walter"
def greetingMsg = "Welcome! ${name}"

name = "White"

println greetingMsg

Output

Welcome! Walter

def name = "Walter"
def greetingMsg = "Welcome! ${->name}"

name = "White"

println greetingMsg

Output

Welcome! White

In the first script, the GString ${name} is evaluated when greetingMsg is defined, capturing the value of name at that moment, which is "Walter".

In the second script, the GString ${->name} uses a closure. The closure is evaluated at the moment of printing, not when greetingMsg is defined. Since name has changed to "White" by the time the closure is executed, it reflects the updated value.

Currying in Groovy

Currying in Groovy is a technique that allows you to create a new closure by pre-filling some of the parameters of an existing closure. This effectively reduces the number of arguments needed to call the new closure, making it a convenient way to create specialized functions from a general one.

def getUsers = { groupId, role, status ->
    // Simulate fetching users from a database or API
    println "Fetching users from group ${groupId} with role ${role} and status ${status}"
}

def getHRUsers = getUsers.curry("HR")

getHRUsers("Admin", "Active")
getHRUsers("Viewer", "Inactive")

def getActiveUsers = getUsers.rcurry("ACTIVE")

getActiveUsers("Development", "Tester")

def getAllDevelopers = getUsers.ncurry(1, "Developer")

getAllDevelopers("IT", "Active")
getAllDevelopers("Marketing", "Suspended")

Output

Fetching users from group HR with role Admin and status Active
Fetching users from group HR with role Viewer and status Inactive
Fetching users from group Development with role Tester and status ACTIVE
Fetching users from group IT with role Developer and status Active
Fetching users from group Marketing with role Developer and status Suspended

In Groovy, there are three currying methods used to partially apply parameters to closures:

curry(): Fixes the leftmost parameters of a closure.

Example: closure.curry(value1) fixes value1 for the first parameter.
rcurry(): Fixes the rightmost parameters of a closure.

Example: closure.rcurry(valueN) fixes valueN for the last parameter.
ncurry(): Fixes parameters at a specific index in the closure.

Example: closure.ncurry(index, value) fixes the parameter at the given index.
These methods simplify repeated calls by pre-filling some arguments, improving code readability and maintainability.

Metaprogramming

In simple terms metaprogramming refers to writing code that can create, modify, generate and analyze other programs.It accepts other codes as its data and do some operations with it.

A best example for metaprogamming is the eval function in JavaScript, which accepts a string of JavaScript code and executes it.

Metaprograms are frequently used in everyday applications. For instance, integrated development environments (IDEs) like Visual Studio Code and IntelliJ IDEA use metaprogramming techniques to analyze code for syntax or compile-time errors even before the code is executed. The IDEs essentially act as programs that process and check the user's code for errors before runtime.

Metaprogramming in Groovy

Groovy supports two types of metaprogramming:

Runtime Metaprogramming:

Runtime metaprogramming in Groovy allows us to modify or extend the behaviour of classes and objects dynamically at runtime.

In Groovy, the invokeMethod() is a special method available in Groovy objects that is triggered when an undefined method is called on an object. By overriding invokeMethod(), we can customize how undefined method calls are handled.

Additionally, Groovy provides getProperty() and setProperty() methods. These methods intercept operations related to getting or setting properties in a class, allowing you to implement custom logic, such as validation, before retrieving or modifying property values.

class User{
    def name
    def age
    def email

    void setProperty(String name, Object value){
        if (value == null){
            value = ""
        }
        this.@"$name" = value.toString()
    }

    void print(){
        println "Name : ${name}, age : ${age}, email : ${email}"
    }
}

User user = new User()

user.name = "arun"
user.age = 2
user.email = null

user.print()

Output

Name : arun, age : 2, email :

Command Chains

Command chains in Groovy offer a concise and expressive way to call methods without using parentheses or dots (.) between method calls. This feature can make your code more readable, especially when you want to write more fluid and natural-looking expressions.

A command chain lets you call methods as if you were writing a sentence. Let’s look at an example:

class Car {
    def start() {
        println "Car started"
        return this
    }

    def drive() {
        println "Driving"
        return this
    }

    def stop() {
        println "Car stopped"
        return this
    }
}

def car = new Car()
car start drive stop

Output

Car started
Driving
Car stopped

In the above example, car start drive stop demonstrates a command chain where methods are called in sequence. Each method returns this, allowing the next method in the chain to be called on the same Car object.

In this blog, we explored various features of Groovy, from its metaprogramming capabilities and dynamic method handling to expressive features like command chains and delegation strategies. Groovy's ability to enhance code readability and flexibility through dynamic behaviour makes it a powerful tool for developers. By understanding and leveraging these features, you can write more intuitive and maintainable code.

If you have any questions, suggestions, or additional insights about Groovy or any other programming topics, please share your feedback in the comments below ?.

以上是Groovy 相对于 Java 的特性和优势的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn