Android反射 - 调用方法

时间:2014-01-25 21:17:46

标签: android reflection

这里我想调用android.view.View :: dispatchPointerEvent方法。当我这样做时,我得到以下异常:

java.lang.IllegalArgumentException: expected receiver of type android.view.View, but got java.lang.Class<android.view.View>
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.infostretch.automateme.Main.injectMyCrap(Main.java:75)
        at com.infostretch.automateme.MainActivity$1.onClick(MainActivity.java:33)
        at android.view.View.performClick(View.java:4202)
        at android.view.View$PerformClick.run(View.java:17340)
        at android.os.Handler.handleCallback(Handler.java:725)
        at android.os.Handler.dispatchMessage(Handler.java:92)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5039)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at com.android.internal.os.ZygoteInit.main(Native Method)
        at dalvik.system.NativeStart.main(Native Method)

这是代码

static void injectMyCrap() {
    Log.i("JSLock-injectMyCrap","I got called");
    Class _class = null;

    try {
        _class = Class.forName("android.view.View");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    Method method = null;
    try {

        method = _class.getMethod("dispatchPointerEvent", MotionEvent.class);
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    }
    try {
        MotionEvent evntDown = MotionEvent.obtain( SystemClock.uptimeMillis(),
                SystemClock.uptimeMillis(),
                MotionEvent.ACTION_DOWN,
                10, 10, 0);
        method.invoke(_class,evntDown);

        MotionEvent evntUp = MotionEvent.obtain( SystemClock.uptimeMillis(),
                SystemClock.uptimeMillis(),
                MotionEvent.ACTION_UP,
                10, 10, 0);
        method.invoke(_class,evntUp);

    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        e.printStackTrace();
    }

}

或者我可能需要创建STUB?我不知道怎么样,有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

您必须将其强制转换为View对象:(查看)method.invoke(_class,eventUp);