0

If i am running this for loop:

Method[] methods = someClass.getDeclaredMethods();
for(Method method: methods){
         /*code*/
   }

Is there a way for me to know at what iteration im currently on. I need to know if a certain method is found and then save the position in the array for that method.

Thanks

forsb
  • 123
  • 9
  • What do you intend to do with the `Method` variable after finding the one you want? – Tim Biegeleisen Nov 17 '20 at 15:55
  • If a method named `setUp`is found that method is supposed to be invoked before every other invoke that the program does. I assume that i may be able to instead save that method if i find it? – forsb Nov 17 '20 at 15:58
  • https://stackoverflow.com/questions/477550/is-there-a-way-to-access-an-iteration-counter-in-javas-for-each-loop – Tarik Nov 17 '20 at 16:12

3 Answers3

1

Update your code as below, to iterate using array length. You would get the index.

Method[] methods = someClass.getDeclaredMethods();
int index = -1;
for(int i =0; i< methods.length; i++){
    Method currentMethod = methods[i];
    index = i;
         /*code*/
}
Gaurav Jeswani
  • 4,410
  • 6
  • 26
  • 47
1

You can either use a conventional loop:

Method[] methods = someClass.getDeclaredMethods();
for (int i = 0; i < methods.length; i ++) {
    Method method = methods[i];
    // i contains your position
}

Or, keep track of i separately:

Method[] methods = someClass.getDeclaredMethods();
int i = 0;
for (Method method: methods) {
    // i contains your position
    i ++;
}
Aplet123
  • 33,825
  • 1
  • 29
  • 55
1

You could use a counter like so:

int counter = 0;
Method[] methods = someClass.getDeclaredMethods();
for(Method method: methods){
    i++;
    /*code*/
}

Or just use a regular for loop:

Method[] methods = someClass.getDeclaredMethods();
for(int i = 0; i < methods.length; i++) {
    /*code*/
}

In both examples i lets you know on what itereration you are.