我嘗試使用反射來爲目標api級別7的應用程序使用自定義列表視圖。必需的文件只能從api級別9獲得,因此我試圖通過反射來解決此問題。我需要找到受保護的方法View.overScrollBy(int,int,int,int,int,int,int,int,boolean)。當我打電話Android中的反射無法正常工作
View.getDeclaredMethods()
和迭代方法[]數組我找到它,但是當我嘗試
View.class.getDeclaredMethod(String name, Class...<?> paramTypes)
我得到一個NoSuchMethodException。我比較了從方法提取的值硬編碼的方法名稱和參數類型的值(通過迭代找到),他們是相同的......
private boolean initCompatibility()
{
Method[] methods = View.class.getDeclaredMethods();
try {
// The name of the Method i am looking for;
String OVERSCROLL_S = "overScrollBy";
for (Method meth : methods) {
if (meth.getName().equals(OVERSCROLL_S)) {
mListView_overScrollBy = meth;
break;
// method found
}
}
// Params for getDeclaredMethod(…)
String methodName = "overScrollBy";
Class[] methodParams = { Integer.TYPE, Integer.TYPE, Integer.TYPE,
Integer.TYPE, Integer.TYPE, Integer.TYPE, Integer.TYPE,
Integer.TYPE, Boolean.TYPE };
// works
Method test = View.class.getDeclaredMethod(methodName,methodParams);
// fails
View.class.getDeclaredMethod(mListView_overScrollBy.getName(),
mListView_overScrollBy.getParameterTypes());
/*
* I also tried this way around and again the first worked and the second
* failed, so the input arguments are not the problem...
* View.class.getDeclaredMethod(mListView_overScrollBy.getName(),
* mListView_overScrollBy.getParameterTypes());
* Method test = View.class.getDeclaredMethod(methodName,methodParams);
*/
return true;
} catch (SecurityException e) {
e.printStackTrace();
return false;
} catch (NoSuchMethodException e) {
e.printStackTrace();
return false;
}
}
我不明白爲什麼總是調用工作在第一時間和不是第二次。有趣的是,當我僅爲View.class.getDeclaredMethod(String name,Class ... <?> paramTypes)調用一次時,它也失敗,無論我使用硬編碼輸入值還是從方法中提取的輸入值都沒有任何區別我在尋找...
有沒有人知道問題是什麼?謝謝
看看我的答案。你能否確認在調試和運行模式下是否拋出異常? –
愚蠢的問題時間!這是你正在運行的真實代碼嗎?你以前調查過的「視圖」有沒有可能是一個不同的類,然後呢?不同的'import',因爲它是一個普通的類名。 – Gray
另一個愚蠢的問題:你在printStackTrace上得到一個輸出嗎?我只是在模擬器中運行你的確切代碼,並沒有得到輸出。此外,在eclipse中調試Android應用程序時,行號esp。退貨不正確。因此,在第二個getDeclaredMethod之後,即使沒有異常拋出,IP也會指向catch塊中的return語句! (經常遇到此類行爲) –