1

In java, is it possible to use a variable in the method name when calling the method? For example, see the following psudeocode:

for (i = 0 through 5)
{
    methodi();
}

where the methods are

method1()
{

}
method2()
{

}
.
.
.
method5()
{

}
user2809114
  • 97
  • 4
  • 15
  • Only with reflection. – PM 77-1 Apr 20 '15 at 23:40
  • No, that is not possible in Java, nor would I recommend it. What are you trying to accomplish here? – JamesB Apr 20 '15 at 23:40
  • 1
    @JamesB - It **is** possible but I wouldn't recommend it either. – PM 77-1 Apr 20 '15 at 23:41
  • Possible duplicate questions: [Is it possible to do getMethodX with a for?](http://stackoverflow.com/questions/29656479/is-it-possible-to-do-getmethodx-with-a-for) and [how to call a java method using a variable name?](http://stackoverflow.com/questions/4138527/how-to-call-a-java-method-using-a-variable-name). – rgettman Apr 20 '15 at 23:43
  • It wasn't something that i necessarily had to do, I was just trying to do it because i have 4 methods called exercise1(),...,exercise4() which were exercises at the end of a homework problem, and that's how I decided to organize them. I am curious why do you both not recommend it? – user2809114 Apr 20 '15 at 23:46
  • PM 77-1 doesn't recommend this because it is prone to error, it can fail very fast. And the `switch` idea is too Java 7- (and I don't recommend the `switch` approach because it's too verbose and harder to maintain). Use the Java 8 approach that's suggested in the duplicate Q/A. – Luiggi Mendoza Apr 20 '15 at 23:51

1 Answers1

1

Why not make a single method with a switch inside?

void method(int val)
{
    switch(val){
    case 1: 
       // method 1 
       break;
    case 2: 
       // method 2 
       break;
    case 3: 
       // method 3
       break;
    default:
       System.out.println("No such method!");
    }

}
John
  • 3,769
  • 6
  • 30
  • 49