android - 在继承方法上使用反射的正确方法

标签 android reflection

我在我的应用程序中使用了 Google Music 应用程序中的 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 (Method)。

我正在 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) {

        }

最佳答案

因为是继承的方法。 getDeclaredMethods() 仅检索在您的 类中声明的方法,而不是其父类(super class)的方法。虽然我从未真正这样做过,但您应该能够调用 getSuperclass() 直到找到声明该方法的类 (AbsListView) 并从中获取该方法。

一个更简单的答案可能只是检查 API 的版本:Programmatically obtain the Android API level of a device?

关于android - 在继承方法上使用反射的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7002028/

相关文章:

Android 的 SensorManager 无法有效注销监听器

reflection - 使用 Go 反射包获取结构字段标签

c# - 如何动态评估 C# 代码?

c# - 通过反射创建的传递方法,作为 Func 参数

android - 允许两台设备使用 wifi 接口(interface)在 Android 上相互查看?

android - 在 Android 中设置 iBeacons 和设备电池生命周期

java - ListView的Android自定义行项目

java - eclipse : key on Android AES encryption and decryption

c# - 实例化一个内部类并将其转换为给定类型

c# - c#中的基本接口(interface)