![](/img/trans.png)
[英]Java reflection getDeclaredMethod throws NoSuchMethodException
[英]getDeclaredMethod throws exception
我想編寫一個通過rpc進行通信的客戶端服務器應用程序。 該代碼與沒有參數的函數配合得很好。 但是,當我嘗試用一個參數調用一個函數(不支持更多參數)時,它給了我一個“ NoSuchMethodException”。
以下是重要部分:
我要調用的函數:(rpcserver.CarPark.in)
public boolean in(int num) {
if(!closed) {
if (num <= (maxLots - curLots)) {
curLots += num;
return true;
}
}
return false;
}
public boolean in() {
if(!closed) {
if (curLots < maxLots) {
curLots += 1;
return true;
}
}
return false;
}
這是調用函數的代碼:(我將procedure [0]用作函數名稱,將[1]用作參數。
if(procedure.length == 1) {
try {
Method method = CarPark.class.getDeclaredMethod((String)procedure[0]);
return method.invoke(park);
} catch (Exception e) {
throw new Exception("Server couldn't find a fitting procedure.");
}
} else {
// length of 2, more isn't possible
try {
System.out.println((String)procedure[0] + ", " + procedure[1].getClass());
Method method = CarPark.class.getDeclaredMethod((String)procedure[0], procedure[1].getClass());
return method.invoke(park,procedure[1]);
} catch (Exception e) {
throw new Exception("Server couldn't find a fitting procedure." + e);
}
}
奇怪的是,該函數返回以下內容: java.lang.NoSuchMethodException: rpcserver.CarPark.in(java.lang.Integer)
但是,println命令為我提供了以下內容: in, class java.lang.Integer
那么,為什么我可以調用沒有參數但有參數問題的過程呢?
謝謝
問題在於,您嘗試獲取的CarPark.in
版本采用原始整數,而getDeclaredMethod
正在尋找采用java.lang.Integer
,這不是同一回事。 如果將int.class
或Integer.TYPE
傳遞給getDeclaredMethod
,則會看到它能夠正確找到該方法。
不用看完整的代碼就可以為您提供一個適合您的解決方案,這很容易,但是請記住原始類型及其裝箱的等效項之間的區別,並要警惕自動裝箱 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.