4

我正在尝试在 Java 7 中使用 MethodHandles。

我在这里有一堂课:

public class TestCase {
    MethodType mt;

    public static void main(String args[])
    {
        Android a = new Android();
        MethodHandleExample.doSomething(a);
    }
}

class Android {
    public void thisIsMagic()
    {
        System.out.println("Might be called from the method handel");
    }
}

并且方法句柄示例调用在这个类中:

public class MethodHandleExample {

    public static void doSomething(Object obj)
    {
        MethodHandle methodHandle = null ;
        MethodType mt = MethodType.methodType(void.class);
        MethodHandles.Lookup lookup = MethodHandles.lookup();

        try{
            try {
                methodHandle = lookup.findVirtual(obj.getClass(),"thisIsMagic",mt);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            } catch (IllegalAccessException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
        finally {

        }
        try {
            methodHandle.invoke();
        } catch (Throwable throwable) {
            throwable.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
}

但是当我尝试运行此代码时,会出现如下异常:

java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(Android)void to ()void
    at java.lang.invoke.MethodHandle.asType(MethodHandle.java:691)
    at java.lang.invoke.InvokeGeneric.dispatch(InvokeGeneric.java:103)
    at com.generic.exception.AnnotationParser.doSomething(AnnotationParser.java:35)
    at com.generic.exception.TestCase.main(TestCase.java:18)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

我得到的例外是在线:

 methodHandle.invoke();

不确定在这种情况下如何调用底层方法。

4

2 回答 2

6

添加:

methodHandle.invoke(obj)

您必须提供一个对象来运行该方法。

于 2013-02-10T09:07:16.473 回答
1

您需要调用对象的方法句柄。

methodHandle.invoke(obj);
于 2013-02-10T10:00:18.273 回答