2017-06-29 92 views
1

我在尝试在同一个类中的方法上调用getMethod时遇到NoSuchMethodException,并且没有从哈希映射中抽取字符串名称的参数。任何建议,或只给出方法的字符串名称在同一类中调用方法的另一种方法? 获得方法的调用是在这里:Java反射NoSuchMethodException在引用同一类中的方法时

if (testChoices.containsKey(K)) { 
     String method = testChoices.get(K); 
     System.out.println(method); 

     try { 
      java.lang.reflect.Method m = TST.getClass().getMethod(method); 
      m.invoke(testChoices.getClass()); 
     } catch (NoSuchMethodException e1) { 
      // TODO Auto-generated catch block 
      System.out.println("No method found"); 
      e1.printStackTrace(); 
     } catch (SecurityException e1) { 
      // TODO Auto-generated catch block 
      e1.printStackTrace(); 


     } catch (IllegalAccessException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (IllegalArgumentException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } catch (InvocationTargetException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 

一个我试图调用的方法是在这里:

private static void testgetDomainLic() throws IOException { 

,map条目被称为是在这里:

testChoices.put(1, "testgetDomainLic"); 
+0

静态方法testgetDomainLic()在TST类中定义,还是在它的超级接口中定义? –

+0

TST只是testgetDomainLic()所在的类的一个实例。 – user8232299

+0

我改变它调用Class.forName直接定义的类,它仍然没有找到方法。 – user8232299

回答

0

我认为您的情况您可以将getMethod更改为getDeclaredMethodgetMethod只返回公共方法。

这里的打嗝是他们实际上有不同的语义其他比他们是否返回非公共方法。 getDeclaredMethod仅包括宣称的而不是继承的方法

因此,例如:

class Foo { protected void m() {} } 
class Bar extends Foo {} 
Foo actuallyBar = new Bar(); 
// This will throw NoSuchMethodException 
// because m() is declared by Foo, not Bar: 
actuallyBar.getClass().getDeclaredMethod("m"); 

在这样的最坏的情况下,你通过所有声明的方法必须循环,像这样:

Class<?> c = obj.getClass(); 
do { 
    for (Method m : c.getDeclaredMethods()) 
     if (isAMatch(m)) 
      return m; 
} while ((c = c.getSuperclass()) != null); 

还是占接口(主要是因为他们可以现在申报静态方法):

List<Class<?>> classes = new ArrayList<>(); 
for (Class<?> c = obj.getClass(); c != null; c = c.getSuperclass()) 
    classes.add(c); 
Collections.addAll(classes, obj.getClass().getInterfaces()); 
Method m = classes.stream() 
        .map(Class::getDeclaredMethods) 
        .flatMap(Arrays::stream) 
        .filter(this::isAMatch) 
        .findFirst() 
        .orElse(null); 

而作为一个附注,你可能是不需要需要调用m.setAccessible(true),因为你在声明它的类中调用它。尽管如此,在其他情况下这是必要的。

+0

这对我很有用,非常感谢 – user8232299

0

我不是专家,但尝试改变你的方法,所以它不是私人的。

私有方法可以通过反射来调用,但是还有额外的步骤。请参阅Any way to Invoke a private method?

+1

OP正在收到NoSuchMethodException。问题出在'getMethod()' - 而不是'invoke()'。 –

+0

另外,我已经尝试删除私人但它仍然给出相同的错误 – user8232299

+0

行。所以我正在解决他们尚未解决的问题! –

相关问题