Karz
Karz

Reputation: 557

Call functions put in array

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 !

Upvotes: 2

Views: 81

Answers (2)

aioobe
aioobe

Reputation: 421290

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(); } });

Upvotes: 2

Mike Tunnicliffe
Mike Tunnicliffe

Reputation: 10772

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

Here's some tutorials on how to get started:

Upvotes: 0

Related Questions