1

I have function A, function B, and function C

I am trying to call one of these function randomly (A or B or C) from Main.

How can i go about doing it?

Can i put the functions in an arraylist called FunctionList

Then do the following?

int x = (int)(Math.random() * Functionlist.size());
FunctionCall = FunctionList.get(x) 
Pshemo
  • 113,402
  • 22
  • 170
  • 242
user872009
  • 342
  • 2
  • 3
  • 13
  • Possible duplicate - http://stackoverflow.com/questions/2752192/array-of-function-pointers-in-java – pyrospade Aug 01 '12 at 23:29
  • Follow the answer in the comment above – pyrospade Aug 01 '12 at 23:30
  • What do you mean by function? Is it some method like `functionA()` or maybe some [strategy](http://en.wikipedia.org/wiki/Strategy_pattern) class `FunctionA`? – Pshemo Aug 01 '12 at 23:31
  • I think he was hoping you could treat a funtion/method as an object, like you can do in other languages. – jahroy Aug 01 '12 at 23:35
  • Another option would be to use reflection, though the comment above is likely a better approach. – jahroy Aug 01 '12 at 23:36

3 Answers3

2

If the number of functions is small, the easiest way would be a switch,

switch((int)(Math.random()*NUM_FUNCTIONS) {
    case 0:
        functionA();
        break;
    case 1:
        functionB();
        break;
  //  ...
}
Daniel Fischer
  • 174,737
  • 16
  • 293
  • 422
0

Java doesn't support function pointers. One workaround would be to name your functions methodically, i.e. f1, f2, f3, etc... and then create a Method object based off of that pattern. For example, using the function names f1, f2, f3, you could do this:

java.lang.reflect.Method method;
try {
  methodName = "f" + String.valueOf((int) Math.random()*NUM_FUNCTIONS);
  method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..); 
} catch (SecurityException e) {
  // ...
} catch (NoSuchMethodException e) {
  // ...
}

Then call the function like so:

try {
  method.invoke(obj, arg1, arg2,...);
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {

*This answer is heavily borrowed from here.

Community
  • 1
  • 1
laker
  • 549
  • 1
  • 4
  • 17
0

I'd mimic function objects the standard way by creating -maybe anonymous- classes implementing some interface Function<T> with a method call(T arg), or even Runnable, if there's no argument. Instances of those can be put into a collection

Heiko Schmitz
  • 240
  • 1
  • 4