Jarrel Costiniano
Jarrel Costiniano

Reputation: 27

Dynamically call methods from a variable

I'm consuming this SDK on my project: Pollexor

I would like to create a generic/main method to accept any request from other methods.

static String thumborGetURL(String alias, String imageUrl) {
    thumborUrlBuilder( alias, imageUrl )
            .crop( 299, 296, 301, 297 )
            .resize( 300, 300 )
            .toUrl()
}

private static ThumborUrlBuilder thumborUrlBuilder(String alias, String imageUrl) {
    Thumbor thumbor = Thumbor.create( 'http://localhost:8000', 'MY-SECURITY-KEY' )
    thumbor.buildImage( imageUrl )
}

static String thumborCrop(String alias, String imageUrl) {
    thumborGetURL( alias, imageUrl )
}

How I can make the .crop, .resize, .toUrl and other methods and their parameters from the SDK to be called dynamically from one variable of type Map e.g.? Is that possible?

Upvotes: 1

Views: 1421

Answers (1)

Opal
Opal

Reputation: 84824

If you have method's name and it's arguments you can try the following:

def method(String a, String b) {
    println "a: $a, b: $b"
}

def args = ['c', 'd']
def name = 'method'

"$name"(*args)

If list's arguments length is invalid an exception will be thrown.

Upvotes: 1

Related Questions