2017-06-29 91 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

行。所以我正在解決他們尚未解決的問題! –

相關問題