当方法没有参数时,可以简化此Groovy代码吗?

时间:2019-09-14 12:23:43

标签: jenkins groovy

我正在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条件检查?

2 个答案:

答案 0 :(得分:1)

groovy对象具有invokeMethod方法,该方法可以隐藏if

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

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

答案 1 :(得分:0)

如果不深入元编程,则可以(错误地)使用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 ] : [] ) )