加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

如何将Groovy类构造函数转换为Closure?

发布时间:2020-12-14 16:24:45 所属栏目:大数据 来源:网络整理
导读:所以Groovy有这种相对方便的语法来将方法转换为闭包,例如 [1,2,3].each { println it }// is equivalent to[1,3].each this.println 但是我如何转换类构造函数,例如 [1,3].collect { new Thing( it ) }// is equivalent to[1,3].collect ???? Groovy的反射有
所以Groovy有这种相对方便的语法来将方法转换为闭包,例如

[1,2,3].each { println it }

// is equivalent to

[1,3].each this.&println

但是我如何转换类构造函数,例如

[1,3].collect { new Thing( it ) }

// is equivalent to

[1,3].collect ????

Groovy的反射有Thing.constructors List来检查,但我无法弄清楚在Thing.constructors [0]中放置&符号的位置.

解决方法

您可以使用 invokeConstructor metaClass method调用给定参数的构造函数.

class Thing {
    Thing(Integer num) { this.num = num }
    Integer num
}

[1,3].collect Thing.metaClass.&invokeConstructor

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读