NoSuchMethodException与反射有关

时间:2011-04-14 17:53:48

标签: 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 {
        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()并且有相同的异常,所以我认为它是其他东西(除非这没有找到超类方法?)。想法?

4 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

我认为应该是:

String methodName = "getHeuristic" + mystring;

但我不知道你的编曲方式。那里的变量“启发式”是什么?

答案 2 :(得分:0)

我建议您使用像commons-beanutils这样的库,而不是直接反思的不愉快。

此外,您的示例代码有一个空的catch块,最好避免使用。

答案 3 :(得分:0)

我认为问题在于你的变量myString未设置为它应该是什么。我会插入一些调试语句,以确保methodName完全符合您的想法。