How to call base void method using method descriptor class in java 7?

I am trying to play with MethodHandles in Java 7.

I have a class here:

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"); } } 

And the calls to the example method descriptor are here in this class:

 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. } } } 

but when I try to run this code, I get the following exception:

 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) 

The exception that I get is on the line:

  methodHandle.invoke(); 

Not sure how to call the base method in this case.

+4
source share
2 answers

Add

 methodHandle.invoke(obj) 

You must specify an object to run the method.

+4
source

You need to call the method handle for the object.

 methodHandle.invoke(obj); 
+2
source

All Articles