0

I want to call multiple methods in a string according to the for loop condition.

This code should help you understand what I am looking for:

public void onItemClick(View view, int position) {
    for (count=0;count<=25;count++){
        if (count==position){
            String methodCall="A"+count+"List()";
            A0List()=methodCall;
        }
    }
}

A0List(){
     //Body 
     //when count=0 this method is called
}

A1List(){
    //body
    //when count=1 this method is called
}

// ...

A25List(){
   //body
   //when count=25 this method is called
}

I use this code on my Android app to reduce click listener code.

I am looking for a solution which avoids an if-else-if ladder loop.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Palash Dey
  • 69
  • 1
  • 7
  • You could do it using reflection but I won't recommend it. Instead, I believe the code in your `AXList()` methods would be quite similar, so you should have just one method and pass the number as a parameter. Can you show the code in a couple of those methods to confirm this? – Kartik Jan 03 '19 at 23:39
  • Using a adapter to put value in another class or Andorid activity – Palash Dey Jan 04 '19 at 00:37

1 Answers1

1

What you are asking is covered here: How do I invoke a Java method when given the method name as a string?

But in most situations, preferable to reflection would be explicitly mapping. This way your function names don't have to be bound to a position by name. The mapping has to be done somewhere. I fail to see how the method name is the proper place for that:

Map<Integer, Runnable> functionMap = new HashMap<>();
functionMap.put(0, () -> A0List());
functionMap.put(1, () -> {/*A1List body*/});
// etc
functionMap.put(25, () -> someMeaningfulMethodName());

Then your function would be:

public void onItemClick(View view, int position) {
    functionMap.getOrDefault(position, () -> {/* handle incorrect position */}).run();
}

Even simpler would be a switch statement:

switch(position)
{
    case 0: A0List(); break;
    case 1: A1List(); break;
    // etc
    case 25: A25List(); break;
    default: /* handle unknown position */ break;
}
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
CJDood
  • 333
  • 3
  • 7
  • thanks. But switch and map it is the same as if-else-if ladder loop. I want more utilize – Palash Dey Jan 04 '19 at 00:22
  • The mapping has to be done somewhere. I don't that doing it in the method name is a good idea, but if you must, this will help https://stackoverflow.com/questions/160970/how-do-i-invoke-a-java-method-when-given-the-method-name-as-a-string – CJDood Jan 07 '19 at 20:11