Can Java store methods in arrays?

后端 未结 5 2145
生来不讨喜
生来不讨喜 2020-12-31 08:55

Well I wrote some code and all I was doing was for loops, but changing which method I called. I tried using a for loop so it\'d be a bit neater (and out of curiosity to see

5条回答
  •  爱一瞬间的悲伤
    2020-12-31 09:50

    You can't call methods like that. But you can using reflection:

    Just change the first line in the while-loop to:

    Method m = myWumps.getClass().getMethod(moveArray[i]); // if the method is void
    m.invoke(myWumps);
    

    (you will have to declare/catch a few exceptions)

    But you'd better avoid reflection, and use the Command pattern instead.

提交回复
热议问题