反射的 NoSuchMethodException 问题
所以,我有一些类似的事情:
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;
}
}
我很困惑......我不断收到 NoSuchMethodException
,但我不知道为什么。我认为问题可能是 myClass 是抽象的,所以我用 getClass() 尝试了这个并遇到了相同的异常,所以我认为这是其他东西(除非这找不到超类方法?)。想法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试使用
getMethod()
而不是getDeclaredMethod
。前者将您限制为特定的类实例,后者包括整个层次结构。另外,我假设启发式(例如“Manhattan”)的大写字母适当?也就是说,通过使用枚举和某种内部策略类可能可以更好地处理类似的事情。然后,您将枚举映射到相关的策略实施。
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.
我认为应该是:
String methodName = "getHeuristic" + mystring;
但我不知道你的如何编译。范围内的变量“启发式”是什么?
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?
我建议您使用诸如 commons-beanutils 之类的库,而不是在直接反射的不愉快中苦苦挣扎。
此外,您的示例代码有一个空的 catch 块,最好避免这种情况。
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.
我认为问题在于您的变量
myString
未设置为应有的值。我会插入一些调试语句以确保methodName
正是您所认为的那样。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 suremethodName
is exactly what you think it should be.