• 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 ...
Marshals:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Method calling

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have following methods say method1(), method2(),�..method15(). I need to call all these method at one place. Is it possible to put them in a loop rather than calling each of them individually. Something like this:
for (int I=1;I<21;I++){
//call methods here
}
 
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Rajat, you can collect all the methods into a Method[] array using the getDeclaredMethods() from Class, and iterate through the array -- but I'm not sure how you would actually call the methods within the loop. I'm not 100% sure it's even possible to call a method whose name (entirely or in part) is in a variable.
 
"The Hood"
Posts: 8521
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Well, it took a bit, and it is not pretty, but it CAN be done using reflection.
 
Scott Appleton
Ranch Hand
Posts: 195
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"invoke"...that's pretty sweet.
Reflection is one thing I just love about Java. I was able to use it to good advantage in a WebColor class I created (which assigns names to all 216 WebSafe colors -- e.g., "WebColor.jade", etc.), but until I saw your invoke method, I didn't realize that you could actually use it to call methods without specifying the precise name of the method.
Beauty is in the eye of the beholder...I think that's some pretty snazzy code.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic