2

for my code in Java I need to call functions for some figures inside a number. In fact, if my number is 464, I have to call functions named assert4 and assert6. I hope that you're understanding. But if I'm right, we can't concatenate a string and a variable to have the name of a function and execute it. For example :

for (int i = 0; i < number.length(); i++) {
    assert + i + (); // For example executing the function assert4
}

So I can't see how I can do it. Thanks for help !

Karz
  • 557
  • 1
  • 6
  • 22

2 Answers2

2

You can do this with reflection using something like YourClass.class.getMethod(...).invoke(...). (See this question for instance.)

However, this is a bit of a code smell and I encourage you to do something like

Map<Integer, Runnable> methods = new HashMap<>();
methods.put(464, YourClass::assert464);
...

for (int i = 0; i < number.length(); i++) {
    methods.get(i).run();
}

If you're on Java 7 or older, the equivalent would be

methods.put(464, new Runnable() { public void run() { assert464(); } });
Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
  • What version of Java is needed in your first code block? – Ascalonian Feb 23 '15 at 13:25
  • Java 8. Released roughly a year ago. – aioobe Feb 23 '15 at 13:27
  • Thank you ! I 've just a little problem because when I declare all my functions in a array and I try to access it with assertionArray[i] in the 'public void run' of your second method, it said me that 'i' is accessed from within inner class... – Karz Feb 23 '15 at 14:19
  • Right, so was that part of an error message? If so, what is the exact full error message? You may need to do `final int j = i;` right before using it in the inner class, and then refer to `j` instead of `i`. – aioobe Feb 23 '15 at 14:23
  • It expect me to declare i as a final var but when I do it (in the beginning of the for loop I write 'final int j = i' and I write 'assertionsArray[j]' it say that it's not a statement... – Karz Feb 23 '15 at 14:45
  • No, you need to do `assertionsArray[j].run()`. – aioobe Feb 23 '15 at 15:57
  • @Krili, please accept the answer that best addresses your question so we get a closure of this thread. – aioobe Mar 04 '15 at 20:02
0

You can call a method using a String name using the reflection API.

Here's some tutorials on how to get started:

Mike Tunnicliffe
  • 10,674
  • 3
  • 31
  • 46