绑定和封闭

pra*_*bha 5 groovy binding closures

我不知道如何在Groovy中对闭包使用绑定。我写了一个测试代码,并在运行它时说,缺少setBinding作为参数传递的闭包上的方法。

void testMeasurement() {
    prepareData(someClosure)
}
def someClosure = {
  assertEquals("apple", a)
}


  void prepareData(testCase) {
    def binding = new Binding()
    binding.setVariable("a", "apple")
    testCase.setBinding(binding)
    testCase.call()

  }
Run Code Online (Sandbox Code Playgroud)

tim*_*tes 6

这对我来说适用于 Groovy 1.7.3:

someClosure = {
  assert "apple" == a
}
void testMeasurement() {
  prepareData(someClosure)
}
void prepareData(testCase) {
  def binding = new Binding()
  binding.setVariable("a", "apple")
  testCase.setBinding(binding)
  testCase.call()
}
testMeasurement()
Run Code Online (Sandbox Code Playgroud)

在这个脚本示例中,setBinding 调用是a在脚本绑定中设置的(从 Closure 文档中可以看到,没有 setBinding 调用)。所以在 setBinding 调用之后,你可以调用

println a
Run Code Online (Sandbox Code Playgroud)

它会打印出“苹果”

因此,要在类中执行此操作,您可以为闭包设置委托(当无法在本地找到属性时,闭包将恢复为该委托),如下所示:

class TestClass {
  void testMeasurement() {
    prepareData(someClosure)
  }

  def someClosure = { ->
    assert "apple" == a
  }

  void prepareData( testCase ) {
    def binding = new Binding()
    binding.setVariable("a", "apple")
    testCase.delegate = binding
    testCase.call()
  }
}
Run Code Online (Sandbox Code Playgroud)

它应该a从委托类中获取值(在本例中为绑定)

本页介绍了委托的使用和闭包中变量的作用域

实际上,您应该能够使用简单的 Map 来代替使用 Binding 对象,如下所示:

  void prepareData( testCase ) {
    testCase.delegate = [ a:'apple' ]
    testCase.call()
  }
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!