【发布时间】:2011-08-09 19:46:10
【问题描述】:
我在我的应用程序中使用了 Google 音乐应用程序中的 TouchInterceptor 类。此类允许您将列表项拖放到列表中的不同位置。
TouchInterceptor 类调用了一个名为 smoothScrollBy 的方法。此方法仅在 API 8+ 中可用。
我想在 API 7+ 上定位我的应用程序,所以我需要使用反射来执行 smoothScrollBy 只有当它存在时。
在 TouchInterceptor 的构造函数中,我添加了以下内容:
Method[] ms = this.getClass().getDeclaredMethods();
if (ms != null) {
for (Method m : ms) {
if (m != null && m.toGenericString().equals("smoothScrollBy")) {
Class[] parameters = m.getParameterTypes();
if (parameters != null && parameters.length == 1 && parameters[0].getName().equals("int")) {
mSmoothScrollBy = m;
}
}
}
}
这应该找到smoothScrollBy方法并将其分配给TouchInterceptor的一个新成员变量mSmoothScrollBy(方法)。
我正在 Android 2.2 (API 8) 模拟器上进行调试,不幸的是,该方法从未找到。我的猜测是 getDeclaredMethods() 不会在数组中返回它,因为 smoothScrollBy 是 AbsListView 的一个方法,它被 ListView 继承,最终被 TouchInterceptor 继承。
在调用 getClass().getDeclaredMethods() 之前,我尝试将其转换为 AbsListView,但没有成功。
如何正确获取 smoothScrollBy 以便在可用时调用它?
更新:
我也尝试了以下方法,但无济于事:
Method test = null;
try {
test = this.getClass().getMethod("smoothScrollBy", new Class[] { Integer.class });
}
catch (NoSuchMethodException e) {
}
【问题讨论】:
标签: android reflection