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 !

2 Answers 2

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(); } });
Sign up to request clarification or add additional context in comments.

7 Comments

What version of Java is needed in your first code block?
Java 8. Released roughly a year ago.
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...
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.
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...
|
0

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

Here's some tutorials on how to get started:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.