I tried using reflection to use a custom List View for an App with target api level 7. The necessary fileds are only available from api level 9 so I attempted to fix that via reflection.
I need to find the protected Method View.overScrollBy( int,int,int,int,int,int,int,int,boolean). When i call
View.getDeclaredMethods()
and iterate over the Method[] array i find it, but when I try
View.class.getDeclaredMethod(String name, Class...< ? > paramTypes)
I get a NoSuchMethodException. I compared the hard coded Method Name and parameterType values with the values extracted from the method (found via iteration) and they are identical…
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;
}
}
I do not understand why the call always works the first time and the does not the second time. Interestingly it also fails when i call only once for View.class.getDeclaredMethod(String name, Class…< ? > paramTypes) and it does not make any difference whether i use the hard coded input values or the one extracted from the method I am looking for…
Does anybody know what the problem is? Thanks
This is very interesting, but it is not Android-specific, I think.
I wrote this small test in plain Java:
In eclipse, if I debug it, the three m1,m2 and m3 are printed. However, if I run it, a
NoSuchMethodExceptionis thrown when trying to get m3.UPDATES:
carrdeclaration to use method 0 instead of 1:Class<?>[] carr = m[0].getParameterTypes();as Gray suggested. Now it runs ok but throws exception in debug mode. This means different method order for the returned arraym.