Tran Tam
Tran Tam

Reputation: 699

Convert string to function

On the view, I have hidden field:

<g:hiddenField name="pageName" value="savePage1"/>

then on controller (when form submitted) I have

params.pageName = savePage1

I also have function savePage1()

I tried to transform string to function but it doesn't work:

params.pageName + "()"

How can I call that function with given params.pageName?

Please help, thanks.

Upvotes: 1

Views: 79

Answers (2)

Igor
Igor

Reputation: 34011

In your example you are just concatenating a string, not calling a method. Instead, what you want is dynamic method invocation. Assuming your savePage method is in this:

String pageName = params.pageName
this."$pageName"()

The catch here is it seems like you are trusting user input, so you should make sure that pageName is in an approved whitelist, or you leave yourself exposed to some major vulnerabilities:

String pageName = params.pageName

if (!pageName in [ 'savePage1', 'savePage2' /* ... */]) {
    throw SomeException('Invalid pageName')
}

this."$pageName"()

Although I believe it's a little less performant, you could probably call Eval.me instead too, though the above approach is preferred.

Upvotes: 2

toske
toske

Reputation: 1754

One way I can think of is to create map of all callback functions like :

private def callbacks = [ 'savePage1' : { your();code();here(); },
                  'savePage2'  :{ some();other();code();here(); ]

And than call these functions like :

if(callbacks[params.pageName]){ 
   callbacks[params.pageName]()
}

Beauty of groovy - using closures. If you have savePage1 and savePage2 defined as method, above map would look like

private def callbacks = ['savePage1' : this.&savePage1, 'savePage2' : this.&savePage2 ]

and than, again call it same way

if(callbacks[params.pageName]){ 
   callbacks[params.pageName]()
}

Upvotes: 1

Related Questions