Loading [MathJax]/jax/output/CommonHTML/config.js
前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >Groovy中 使用Tap方法轻松创建对象

Groovy中 使用Tap方法轻松创建对象

原创
作者头像
白石
修改于 2019-08-22 06:33:18
修改于 2019-08-22 06:33:18
1.8K0
举报
文章被收录于专栏:白石白石

使用Tap方法轻松创建对象

Groovy 2.5.0将tap方法添加到所有对象并更改with方法的方法签名。 在上一篇文章 中,我们已经了解了with方法。在Groovy 2.5.0中,我们可以为with方法添加一个额外的boolean参数。 如果值为false(默认值),则with方法必须返回与闭包调用返回的值相同的值。如果值为true,则返回调用with方法的对象实例。 新的tap方法是with(true)的别名,所以它总是返回对象实例。

在第一个例子中,我们使用tap方法创建一个新的Sample对象并设置属性值并调用Sampleclass的方法:

代码语言:txt
AI代码解释
复制
/**
 * Sample class with some properties
 * and a method.
 */
class Sample {
     
    String username, email
     
    List<String> labels = []
     
    void addLabel(value) {
        labels << value
    }
     
}
 
// Use tap method to create instance of
// Sample and set properties and invoke methods.
def sample =
        new Sample().tap {
            assert delegate.class.name == 'Sample'
             
            username = 'mrhaki'
            email = 'email@host.com'
            addLabel 'Groovy'
            addLabel 'Gradle'
             
            // We use tap, an alias for with(true),
            // so the delegate of the closure,
            // the Sample object, is returned.
        }
 
assert sample.labels == ['Groovy', 'Gradle']
assert sample.username == 'mrhaki'
assert sample.email == 'email@host.com'

在下面的示例中,我们使用with方法来演示使用不同参数值的多个调用的差异:

代码语言:txt
AI代码解释
复制
/**
 * Sample class with some properties
 * and a method.
 */
class Sample {
     
    String username, email
     
    List<String> labels = []
     
    void addLabel(value) {
        labels << value
    }
     
}
 
// Use with method to create instance of
// Sample and set properties and invoke methods.
def sample1 =
        new Sample().with {
            assert delegate.class.name == 'Sample'
 
            username = 'mrhaki'
            email = 'email@host.com'
            addLabel 'Groovy'
            addLabel 'Gradle'  
        }
        
// With method returns the result
// from the closure. In the previous
// case the return result is null,
// because the last statement addLabel
// is used as return value. addLabel has
// return type void.
assert !sample1
 
 
// Use with method to create instance of
// Sample and set properties and invoke methods.
def sample2 =
        new Sample().with {
            assert delegate.class.name == 'Sample'
 
            username = 'mrhaki'
            email = 'email@host.com'
            addLabel 'Groovy'
            addLabel 'Gradle'
             
            // Explicitly return delegate of
            // closure, which is the Sample object.
            return delegate
        }
 
assert sample2.labels == ['Groovy', 'Gradle']
assert sample2.username == 'mrhaki'
assert sample2.email == 'email@host.com'
 
 
// Use with method to create instance of
// Sample and set properties and invoke methods.
def sample3 =
        new Sample().with(true) {
            assert delegate.class.name == 'Sample'
 
            username = 'mrhaki'
            email = 'email@host.com'
            addLabel 'Groovy'
            addLabel 'Gradle'
             
            // We use with(true), so the
            // delegate of the closure, the Sample
            // object, is returned.
        }
 
assert sample3.labels == ['Groovy', 'Gradle']
assert sample3.username == 'mrhaki'
assert sample3.email == 'email@host.com'

使用with方法的一个很好的用例是使用来自对象的值将对象转换为另一种类型。 在下一个例子中,我们使用来自Sample对象的值来创建一个新的String

代码语言:txt
AI代码解释
复制
/**
 * Sample class with some properties
 * and a method.
 */
class Sample {
     
    String username, email
     
    List<String> labels = []
     
    void addLabel(value) {
        labels << value
    }
     
}
 
def sample =
        new Sample().tap {
            username = 'mrhaki'
            email = 'email@host.com'
            addLabel 'Groovy'
            addLabel 'Gradle'
        }
 
// The with method can be very useful to
// transform object to another type using
// values from the object.
def user = sample.with { "$username likes ${labels.join(', ')}." }
 
assert user == 'mrhaki likes Groovy, Gradle.'

用Groovy 2.5.0编写。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
Groovy-拾遗
许多以前使用 C++ 的开发人员会怀念操作符重载,例如 + 和 -。虽然它们很方便,但是被覆盖的操作符的多态实质会造成混淆,所以操作符重载在 Java 语言中被取消了。这个限制的好处是清晰:Java 开发人员不必猜想两个对象上的 + 是把它们加在一起还是把一个对象附加到另一个对象上。不好的地方则是丧失了一个有价值的简写形式。
白石
2019/08/23
1.7K0
Groovy快速入门看这篇就够了
在前面我们学习了为什么现在要用Gradle?和Gradle入门前奏两篇文章,对Gradle也有了大概的了解,这篇文章我们接着来学习Groovy的基础,要想学好Gradle,Groovy是必须要掌握的。Groovy仅凭一篇文章是介绍不完的,这里会带大家快速的入门Groovy,讲解Groovy和Java不同的部分,想要更多了解Groovy可以查看Groovy官方文档和Groovy API文档。
用户1269200
2018/10/25
15.5K0
Groovy 使用Builder AST 转换为流式API
从Groovy 2.3开始,我们可以使用@Builder AST转换轻松地为我们的类创建一个流畅的API。 我们可以将注释应用于我们的类,结果类文件将具有支持流畅API的所有必要方法。 我们可以自定义如何使用不同的注释参数生成流畅的API。 在Groovy代码中,我们已经可以使用with方法 有一个简洁的方法来设置属性值或使用 命名的构造函数参数。 但是如果我们的类需要从Java中使用,那么为Java开发人员提供一个流畅的API来为我们的Groovy类做很好。
白石
2019/09/18
1K0
使用Groovy实现Domain-Specific Languages 二
In Groovy number types are considered equal to any other types. As such, it is possible to enhance numbers by adding properties or methods to them. This can be very handy when dealing with measurable quantities for example. Details about how existing classes can be enhanced in Groovy are found in the extension modules section or the categories section.
2022/07/10
5530
[Android Gradle] 搞定Groovy闭包这一篇就够了
做Android开发的同学,对Gradle肯定不陌生,我们用它配置、构建工程,可能还会开发插件来促进我们的开发,我们必须了解Gradle,而不仅限于只会当配置构建工具,我想学习它,于是就有了这一系列的文章。
Android技术干货分享
2019/03/27
1.4K0
[Android Gradle] 搞定Groovy闭包这一篇就够了
Groovy 添加带注释的Map构造函数
从Groovy的早期开始,我们可以创建POGO(Plain Old Groovy Objects)类,它们将具有带有Map参数的构造函数。 Groovy在生成的类中自动添加构造函数。我们可以使用命名参数来创建POGO的实例,因为Map参数构造函数。 这只有在我们不添加自己的构造函数且属性不是最终的时才有效。从Groovy 2.5.0开始,我们可以使用@MapConstrutor AST转换注释来添加带有Map参数的构造函数。使用注释我们可以有更多选项来自定义生成的构造函数。例如,我们可以让Groovy使用Map参数生成构造函数,并添加我们自己的构造函数。 属性也可以是final,我们仍然可以使用带有Map参数的构造函数。
白石
2019/08/23
1.2K0
Groovy秘诀 顶
听说java世界里有个Groovy大神!java需要半天处理的事情,Groovy只需要几分钟,是的,几分钟…剩下来的时间,程序员终于有时间泡妹子了,^_^…….技术宅的兄弟,赶紧来看看吧。
白石
2019/08/23
4.7K0
Groovy里自定义JSON输出-JsonGenerator
Groovy 2.5.0增加了通过JsonGenerator实例自定义JSON输出。 将对象转换为JSON字符串值的最简单方法是通过JsonOutput.toJson。 此方法使用默认的JsonGenerator,其JSON输出具有合理的默认值。 但是我们可以使用自定义生成器并创建JSON输出。 要创建自定义生成器,我们使用可通过JsonGenerator.Options访问的构建器。 通过流式的API,我们可以例如忽略输出中带有null值的字段,更改日期的日期格式,并按名称或值的类型忽略字段。 我们可以通过将转换的实现添加为Closure或者实现JsonGenerator.Converter接口来为类型添加自定义转换器。 要获取JSON字符串,我们只需调用生成器的toJson方法。
白石
2019/08/23
2.4K0
Groovy 使用EqualsAndHashCode注解生成equals和hashcode方法
Groovy 1.8中有很多新的字节码生成注释。 其中一个是@EqualsAndHashCode注释。 使用此注释,为类生成equals()和hashCode()方法。 hashCode()方法是使用Groovyorg.codehaus.groovy.util.HashCodeHelper实现的(遵循书中的算法 Effective Java )。 equals()方法查看类的所有单个属性,以查看两个对象是否相同。
白石
2019/09/09
1.9K0
Groovy中 前序和后序树遍历
Groovy中的Node类有depthFirst和breadthFirst方法,可以使用深度优先遍历或广度优先遍历返回Node对象的集合。由于Groovy 2.5.0,我们可以指定是使用preorder(默认值)还是postorder遍历。此外,这些方法现在接受一个“闭包”,该“闭包”将为每个访问的节点调用。Closure将当前“节点”作为第一个参数,第二个参数是当前节点的树级。
白石
2019/08/23
6560
Groovy-15.DSLS
“命令链”功能:允许在顶层语句的方法调用的参数周围省略括号。也就是在参数周围不需要括号,也不需要链接调用之间的点号。 DSL(Domain Specific Languages 领域定义语言)以简化代码,Groovy中的DSL:
悠扬前奏
2019/05/30
3950
Groovy 简单的`@ToString`注解
从Groovy 1.8开始,我们可以使用@ToString注释来轻松创建toString()方法。 我们只需要在类定义中添加注释,我们就可以获得类的属性的格式良好的输出。
白石
2019/09/09
1.6K0
使用Groovy构建DSL
DSL(Domain Specific Language)官方定义为:针对某一领域,具有受限表达性的一种计算机程序设计语言。
肉眼品世界
2021/03/09
1.3K0
使用Groovy构建DSL
Gradle-Groovy语法
Groovy 是一种基于 JVM 的动态语言,他的语法和 Java 相似,最终也是要编译 .class 在JVM上运行。
佛系编码
2019/12/11
1.7K0
Gradle-Groovy语法
第二章 Groovy 基础
Groovy 是基于 JVM 虚拟机的一种动态语言,它的语法和 Java 非常相似,由 Java 入门Groovy,基本上没有任何障碍。Groovy 完全兼容 Java,又在此基础上增加了很多动态类型和灵活的特性,比如支持闭包,支持 DSL,可以说它是一门非常灵活的动态脚本语言。
acc8226
2022/05/17
7260
第二章 Groovy 基础
为什么说 Gradle 是 Android 进阶绕不去的坎
Gradle 作为官方主推的构建系统,目前已经深度应用于 Android 的多个技术体系中,例如组件化开发、产物构建、单元测试等。可见,要成为 Android 高级工程师 Gradle 是必须掌握的知识点。在这篇文章里,我将带你由浅入深建立 Gradle 的基本概念,涉及 Gradle 生命周期、Project、Task 等知识点,这些内容也是 Gradle 在面试八股文中容易遇见的问题。
用户9995743
2022/09/26
2.7K0
为什么说 Gradle 是 Android 进阶绕不去的坎
【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 同时注入普通方法、静态方法、构造方法 )
如果要同时为 Groovy 类注入大量方法 , 使用 Category 分类 或 MetaClass 将每个方法逐个注入 , 这样操作比较繁琐 ;
韩曙亮
2023/03/30
2210
【Groovy】MOP 元对象协议与元编程 ( 方法注入 | 同时注入普通方法、静态方法、构造方法 )
Groovy 闭包
本文介绍了Groovy闭包的有关内容。闭包可以说是Groovy中最重要的功能了。如果没有闭包,那么Groovy除了语法比Java简单点之外,没有任何优势。但是闭包,让Groovy这门语言具有了强大的功能。如果你希望构建自己的领域描述语言(DSL),Groovy是一个很好的选择。Gradle就是一个非常成功的例子。
乐百川
2022/05/05
8060
Groovy基础
以下内容节选自《Android Gradle权威指南》,更多关于《Android Gradle权威指南》的内容请参见http://yuedu.baidu.com/ebook/14a722970740be1e640e9a3e
飞雪无情
2018/08/28
1.6K0
Groovy 使一个类不可变
创建不可变对象,创建后不能更改。 这使得不可变对象在并发和函数编程中非常有用。 要将Java类定义为不可变,我们必须将所有属性定义为readonly和private。 只有构造函数可以设置属性的值。 Groovy文档 具有适用于不可变对象的规则的完整列表。 使类不可变的Java代码很冗长,特别是因为需要重写hashCode(),equals()和toString()方法。
白石
2019/09/09
5780
相关推荐
Groovy-拾遗
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档