groovy - 将闭包范围设置为调用方法

标签 groovy

是否可以将 Groovy 闭包的范围设置为调用方法?请参阅下面的示例代码:

class TestClass {

  def testMethod() {
    def i = 42

    def closure = testClosure()
    closure.resolveStrategy = Closure.DELEGATE_FIRST 
    closure.delegate = this.&testMethod
    closure() // Should print 42.
  }

  def testMethod2() {
    def i = 43

    def closure = testClosure()
    closure.resolveStrategy = Closure.DELEGATE_FIRST 
    closure.delegate = this.&testMethod2
    closure() // Should print 43.
  }

  def testClosure = {
    println i // I get a MissingPropertyException: No such property i
  }
}

def test = new TestClass()
test.testMethod()
test.testMethod2()

最佳答案

不,但您可以将 i 移动到与闭包相同的范围:

class TestClass {

  def i

  def testMethod() {
    i = 42
    testClosure() // Should print 42.
  }

  def testMethod2() {
    i = 43
    testClosure() // Should print 43.
  }

  def testClosure = {
    println i // I get a MissingPropertyException: No such property i
  }
}

def test = new TestClass()
test.testMethod()
test.testMethod2()

关于groovy - 将闭包范围设置为调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32987623/

相关文章:

Jenkins:在声明式管道中使用 XmlSlurper

grails - 在 Grails 中查找 session 用户的公共(public) IP 地址

java - 什么 Javascript 框架与 Grails 集成得很好?

java - JSONAssert - 在指定范围内比较

java - "static this"关键字会带来哪些问题或好处?

reflection - 在 Groovy 中找出方法的名称

java - 将 HTTP post 从 ruby​​ 转换为 java 或 groovy

Groovy:在运行时检查对象是否为字符串

command-line - 直接从 url 启动 groovy 脚本

java - Groovy:如何调用带注释的方法