我試圖在Java 7中如何在java 7中使用方法句柄類來調用底層的void方法?
與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();
不知道我該如何調用底層方法在這種情況下。
在此先感謝。
你爲什麼要編寫自己的類叫做MethodHandle? – 2013-02-10 09:35:36
@JimGarrison:對不起,這是一個錯誤,它應該是'MethodHandleExample'。我也編輯了這個問題。 – sriram 2013-02-10 09:48:10