2012-08-01 55 views
1

我有函数A,函数B和函数C从主函数调用

我想从Main中随机调用其中一个函数(A或B或C)。

我该如何去做呢?

我可以把该功能称为FunctionList

然后执行以下一个ArrayList?

int x = (int)(Math.random() * Functionlist.size()); 
FunctionCall = FunctionList.get(x) 
+0

可能的重复 - http://stackoverflow.com/questions/2752192/array-of-function-pointers-in-java – pyrospade 2012-08-01 23:29:46

+0

按照上面的注释中的回答 – pyrospade 2012-08-01 23:30:18

+0

你是什么按功能划分?它是一种像'functionA()'还是某种[策略](http://en.wikipedia.org/wiki/Strategy_pattern)类'FunctionA'的方法? – Pshemo 2012-08-01 23:31:53

回答

2

如果函数的数量少,最简单的方法将是一个switch

switch((int)(Math.random()*NUM_FUNCTIONS) { 
    case 0: 
     functionA(); 
     break; 
    case 1: 
     functionB(); 
     break; 
    // ... 
} 
+0

谢谢!它工作得很好。 – user872009 2012-08-01 23:45:33

0

Java不支持函数指针。一种解决方法是按照方法命名你的函数,即f1,f2,f3等等,然后根据该模式创建一个Method对象。例如,使用函数名F1,F2,F3,你可以这样做:

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) { 
    // ... 
} 

然后调用函数像这样:

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

*这个答案在很大程度上从here借来的。

0

我会模仿函数对象与方法call(T arg),甚至Runnable创造 - 也许实现一些接口Function<T> anonymous-类的标准方式,如果没有说法。那些实例可以放入一个集合