NoSuchMethodException problem with reflection
So, I've got something along the lines of:
public abstract class myClass {
String myString;
int test;
public myClass(String heuristic) {
mystring = heuristic;
test = heuristicSwitch();
}
public int heuristicSwitch() {
int hTest = 0;
try {
String methodName = "getHeuristic" + myString;
Method actionMethod = myClass.class.getDeclaredMethod(methodName);
hTest = (Integer)actionMethod.invoke(this);
}
catch(Exception e) {
}
return hTest;
}
public int getHeuristicManhattan() {
return 100;
}
}
I'm stumped... I keep getting NoSuchMethodException
开发者_运维问答, but I've no idea why. I thought the problem might have been that myClass is abstract so I tried this with getClass() and had the same exception, so I'm thinking it's something else (unless this doesn't find superclass methods?). Thoughts?
try using getMethod()
instead of getDeclaredMethod
. the former restricts you to the specific class instance, the latter includes the whole hierarchy. Also, i assume the heuristic (e.g. "Manhattan") is capitalized appropriately?
that said, something like this is probably much better handled through the use of enums and some sort of internal strategy class. you then map your enums to the relevant strategy implementation.
I think it should be:
String methodName = "getHeuristic" + mystring;
But i don't know how yours compiles. What is the variable 'heuristic' that is in scope there?
I suggest you use a library such as commons-beanutils rather than struggling with the unpleasantness of direct reflection.
Also, your sample code has an empty catch block, which is best avoided.
I think the problem is that you're variable myString
isn't set to what it should be. I would insert some debug statement to make sure methodName
is exactly what you think it should be.
精彩评论