-2

Is it possible to store void type methods in an arrayList or can you only store methods that have a return value? I want to call any one of up to 15 methods and rather than write:

if(var == 1){
    method1()
}else if(var ==2){
    method2();
}

etc...

by the time you surround with try/catch and a few more lines of code (that repeat for each one) it would be much neater if you could do:

arrayList.get(var); //or something similar

However my methods just "do stuff" as opposed to return a value so if the methods themselves cannot be stored in an array is there somewhere else they can be stored together and extracted with a for loop or by just using the "var" integer?

James A Mohler
  • 11,060
  • 15
  • 46
  • 72

3 Answers3

0

What you are asking for is given precisely by

java.util.ArrayList<java.lang.reflect.Method>

but it seems to me you should be using a switch statement.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

To anyone who comes to look at this post 6 years later like I was, I suggest you have your ArrayList return a String of "". If the value is not used, it wont matter whether it's there or not, but you'll need it to make the compiler happy.

alyssaeliyah
  • 2,214
  • 6
  • 33
  • 80
-1

You cannot store method references in Java.

However, you can create an object of a class that has a defined interface that allows you to invoke the method readily.

public interface VoidMethod {
  public void callMethod();
}

// ...

public class Method1 implements VoidMethod {
  public void callMethod() {
    // your stuff here
  }
}

// ...

public class MethodN implements VoidMethod {
  public void callMethod() {
    // your stuff here
  }
}

Then you can populate an object array with instances of VoidMethod.

Bob Dalgleish
  • 8,167
  • 4
  • 32
  • 42
  • 1
    Of course you can store method references, by getting a Method object reference. The more tricky part is getting the Method object reference you want, usually by reflection. Of course what you suggested is otherwise a reasonable suggestion, just factually wrong. – Kevin Welker Oct 23 '13 at 21:20