so I'm trying to combine multiple methods that sort an array based on different parameters for optimization. The entire method is the same except for this line:
for (int k = i; k >= 0 && currData.METHOD() <= playerData[k].METHOD(); k--) {
//The stuff inside the method is the same
}
Where METHOD is being changed to different accessor methods, to control how the array is being sorted.
I did a little bit of searching and came across Java reflection (I'm not sure what it is though). Could someone explain how I could use that to solve my problem, or another better solution? Thanks.
As long as the variables are stored, you can do something like this:
String what = new Scanner(System.in).nextLine();
System.out.println(what.getClass().getMethod(what).invoke(what));
If I enter the word length as my input, the output is 6. Because the code calls the function I enter on the string. They don't have to be the same variable though, you could do something like:
for (int k = i; k >= 0 && currData.getClass().getMethod(methodName).invoke(currData)
<= playerData[k].getClass().getMethod(methodName).invoke(playerData[k]); k--)
You can also pass arguments to the functions, if you need to, it's the second parameter after the function name. Just make your variables equal to the function name you want called, and bob's your uncle, should work like a charm.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다