【问题标题】:Can this Groovy code be simplified when method has no arguments?当方法没有参数时,这个 Groovy 代码可以简化吗?
【发布时间】:2019-09-14 12:23:43
【问题描述】:

我正在用 Groovy 编写以下动态函数调用,并想知道是否有更简洁的方法来执行以下操作:

    this.actions.each { a ->
        if (a.component) {
            this.context."${a.action}"(a.component)
        } else {
            this.context."${a.action}"()
        }
    }

a.action 的代码可以是没有任何参数的方法,也可以接受映射。有没有办法动态传入a.component,还是我需要对每个方法签名进行某种类型的if/else 条件检查?

【问题讨论】:

  • this.context."${a.action}"(a?.component)
  • 感谢您的建议,但这会导致 > 没有方法签名:projectProperties.call() 适用于参数类型:(null) values: [null] ... 其中projectProperties 是没有任何参数的方法之一。
  • 我认为你需要在问题中有条件

标签: jenkins groovy


【解决方案1】:

groovy 对象有 invokeMethod 可以隐藏 if 的方法

this.context.invikeMethod( a.action, a.component ? [a.component] : null )

[a.component] 在括号中,因为方法可以有 1,2,3... 参数

【讨论】:

    【解决方案2】:

    如果不深入研究元编程,您可能会(误用)spread operator

    def a(){ 42 }
    def a( i ){ i }
    
    def b = 'a'
    def c = [ 22 ]
    
    assert 22 == "${b}"( *c )
    
    c = []
    assert 42 == "${b}"( *c )
    

    应用于你的具体方法:

    this.context."${a.action}"( *( a.component ? [ a.component ] : [] ) )
    

    【讨论】:

      猜你喜欢
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-03
      • 1970-01-01
      相关资源
      最近更新 更多