Java 无反射异常问题

Java 无反射异常问题,java,reflection,Java,Reflection,因此,我得到了一些大致如下的信息: public abstract class myClass { String myString; int test; public myClass(String heuristic) { mystring = heuristic; test = heuristicSwitch(); } public int heuristicSwitch() { int hTest = 0; try {

因此,我得到了一些大致如下的信息:

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()尝试了这一点,但出现了相同的异常,所以我认为这是其他原因(除非这没有找到超类方法?)。想法?

我认为应该是:

String methodName=“getHeuristic”+mystring


但我不知道你的是怎么编译的。什么是范围内的“启发式”变量?

我建议您使用commons beanutils之类的库,而不是与直接反射的不愉快作斗争

另外,您的示例代码有一个空的catch块,这是最好避免的。

尝试使用
getMethod()
而不是
getDeclaredMethod
。前者将您限制到特定的类实例,后者包括整个层次结构。此外,我假设启发式(例如“曼哈顿”)适当地大写


也就是说,通过使用enum和某种内部策略类,这样的事情可能会得到更好的处理。然后将枚举映射到相关的策略实现

我认为问题在于您的变量
myString
没有设置为它应该设置的值。我会插入一些调试语句,以确保
methodName
正是您认为应该的内容。

np:)顺便说一句,如果您到处使用
private
字段,我想这不会编译,这通常是一种很好的做法。这就成功了,谢谢!只要它允许我,我就投赞成票。