sriram
sriram

Reputation: 9022

Calling a group of methods on a object using closures

I have a class called Test and i have following code

def test = new Test()
test.method1(args)
test.method2(args)

And so on. I wish something like this can be done where I can pass all the method calls of test object in a closure and make them work. like

test {
    method1(args)
    method2(args)
}

Is it possible to do so in groovy?

Upvotes: 0

Views: 67

Answers (2)

Justin Piper
Justin Piper

Reputation: 3274

Groovy will let you call a method using a GString in place of the identifier, so if you want to just have a collection of method names you call on the object, you could do something like:

def doTest(final object, final methods, final args) {
    methods.each { object."$it"(*args) }
}

final test = new Object() {
    void method1(final... args) { println "method1 $args" }
    void method2(final... args) { println "method2 $args" }
    void method3(final... args) { println "method3 $args" }
}

doTest test, [ 'method1', 'method2' ], [ 1, 2, 3 ]

Also Groovy has some syntactic sugar for passing maps to a function which could be handy here. If you don't actually want to call each method with the same arguments you could do something like:

def doTest(final Map methods, final object) {
    methods.each { object."$it.key"(*it.value) }
}

doTest test, method1: [ 1, 2, 3 ], method2: [ 4, 5, 6 ]

I could see something like this being useful if you're getting the method names and values from a CSV file or some similar outside source.

Upvotes: 0

Will
Will

Reputation: 14519

Yes, it is possible with Groovy:

test.with {
    method1 args
    method2 args
}

Upvotes: 5

Related Questions