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 ofgetDeclaredMethod. 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.