我有函數A,函數B和函數C從主函數調用
我想從Main中隨機調用其中一個函數(A或B或C)。
我該如何去做呢?
我可以把該功能稱爲FunctionList
然後執行以下一個ArrayList?
int x = (int)(Math.random() * Functionlist.size());
FunctionCall = FunctionList.get(x)
我有函數A,函數B和函數C從主函數調用
我想從Main中隨機調用其中一個函數(A或B或C)。
我該如何去做呢?
我可以把該功能稱爲FunctionList
然後執行以下一個ArrayList?
int x = (int)(Math.random() * Functionlist.size());
FunctionCall = FunctionList.get(x)
如果函數的數量少,最簡單的方法將是一個switch
,
switch((int)(Math.random()*NUM_FUNCTIONS) {
case 0:
functionA();
break;
case 1:
functionB();
break;
// ...
}
謝謝!它工作得很好。 – user872009 2012-08-01 23:45:33
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借來的。
我會模仿函數對象與方法call(T arg)
,甚至Runnable
創造 - 也許實現一些接口Function<T>
anonymous-類的標準方式,如果沒有說法。那些實例可以放入一個集合
可能的重複 - http://stackoverflow.com/questions/2752192/array-of-function-pointers-in-java – pyrospade 2012-08-01 23:29:46
按照上面的註釋中的回答 – pyrospade 2012-08-01 23:30:18
你是什麼按功能劃分?它是一種像'functionA()'還是某種[策略](http://en.wikipedia.org/wiki/Strategy_pattern)類'FunctionA'的方法? – Pshemo 2012-08-01 23:31:53