This week's book giveaway is in the Testing forum.
We're giving away four copies of Data Structures the Fun Way: An Amusing Adventure with Coffee-Filled Examples and have Jeremy Kubica on-line!
See this thread for details.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

passing method names as string

Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Everyone,

i have a situation where I'm passing method name as a string. i need to call this method on a object.

let me make myself clear..

lets say there is a object bankdetails. it has like 100 methods method1(), method2(),...and so on
i have a string object which gets method names like "method1" or "method2" or..
i need to check this string value and call bankdetails.method1 or bankdetails.method2 or... so on based on this string's value.
one way of doing this would be to use multiple if then else statements to see the values and call the appropriate method. in this case if the object has 100 methods then i need to write 100 statements to check for this...
like (if methodname == "method1" then call bankdetails.method1 else if methodname == "method2" then call bankdetails.method2 ..)

i surely feel there should be another way of doing this..

thanks in advance
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You must use the reflection API for this.
Here is a very simple example to execute your methods by name.
Here the bankDetails methods to be executed have no arguments and return nothing.

You would be much easier to understand if you took that bucket off of your head. And that goes for the tiny ad too!
the value of filler advertising in 2021
    Bookmark Topic Watch Topic
  • New Topic