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

装订和封闭groovy

发布时间:2020-12-14 16:22:35 所属栏目:大数据 来源:网络整理
导读:我不知道如何在Groovy中使用绑定与闭包.我写了一个测试代码,在运行它时,它说,在作为参数传递的闭包上缺少方法setBinding. void testMeasurement() { prepareData(someClosure)}def someClosure = { assertEquals("apple",a)} void prepareData(testCase) { d
我不知道如何在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()

  }

解决方法

这适用于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()

在此脚本示例中,setBinding调用在脚本绑定中设置a(如您所见,from the Closure documentation,没有setBinding调用).所以在setBinding调用之后,你可以调用

println a

它会打印出“苹果”

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

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()
  }
}

它应该从委托类中获取值(在这种情况下,绑定)

This page here通过委托的使用和闭包中的变量范围

实际上,您应该能够像这样使用简单的Map,而不是使用Binding对象:

void prepareData( testCase ) {
    testCase.delegate = [ a:'apple' ]
    testCase.call()
  }

希望能帮助到你!

(编辑:李大同)

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

    推荐文章
      热点阅读