gpt4 book ai didi

groovy - 替换 'this' 在 Groovy 中调用方法引用

转载 作者:行者123 更新时间:2023-12-04 20:44:08 26 4
gpt4 key购买 nike

当引用是从实例中获取时,调用非静态方法引用很容易:

class Foo { void funk() { println "okay!" } }
Foo foo = new Foo()
Closure closure = foo.&funk
closure() // okay! is printed

但是如何替换 this什么时候从类中获取方法引用?
class Foo { void funk() { println "okay!" } }
Foo foo = new Foo()
Closure closure = Foo.&funk
// closure.delegate = foo // not helpful
closure()
// => java.lang.IllegalArgumentException: object is not an instance of declaring class

最佳答案

以下解决您的问题:

class Foo { void funk() { println "okay!" } }
Closure closure = { Foo.&funk.rehydrate(delegate, it, it).call() }
Foo foo = new Foo()
closure(foo)

关于groovy - 替换 'this' 在 Groovy 中调用方法引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20842315/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com