sriram
sriram

Reputation: 9022

Groovy how to delegate certain methods to other class methods?

I'm very new to groovy, I wish I would like to do this.

Lets say I have a class called App.groovy.

class App
{
}

I have other class called DelegateClass, which has two methods:

edit
create

In other class, I need do this:

    //class Test
    def app = new App()
    app.editDetails()
    app.createDetails()
    app.editOtherDetails()

I want all methods start with edit* goes to DelegateClass edit method and the same for create* methods.

How can I do that?

Out of curiosity, is the same can be done in java?

Upvotes: 2

Views: 530

Answers (1)

tim_yates
tim_yates

Reputation: 171054

So, say you have this delegate class:

class DelegateClass {
    String create( args ) {
        "create ${args.join(',')}"
    }

    String edit( args ) {
        "edit ${args.join(',')}"
    }
}

Then you could use methodMissing in your App class:

class App {
    DelegateClass delegate = new DelegateClass()

    def methodMissing( String name, args ) {
        if( name.startsWith( 'create' ) ) {
            delegate.create( args )
        }
        else if( name.startsWith( 'edit' ) ) {
            delegate.edit( args )
        }
    }
}

So all the following works:

def app = new App()
assert app.editDetails() == 'edit '
assert app.editDetails( 'foo' ) == 'edit foo'
assert app.editDetails( 'foo', 'bar' ) == 'edit foo,bar'
assert app.createDetails( 'tim' ) == 'create tim'
assert app.createOtherDetails() == 'create '

With java, there's no such thing as methodMissing, so you'd need to send strings describing the method to call to a centralised handler method, and have that call the method you want.

Upvotes: 4

Related Questions