Created
June 15, 2023 13:11
-
-
Save szeiger/969c41dfd222f4c1d90d46cf57226be5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.invoke.MethodHandle; | |
import java.lang.invoke.MethodHandles; | |
public class Foo { | |
static int normalArray(java.lang.invoke.MethodHandle mh, Object[] args) throws Throwable { | |
return (int)mh.invokeWithArguments(args); | |
} | |
static int polyArray(java.lang.invoke.MethodHandle mh, Object[] args) throws Throwable { | |
return (int)mh.invoke(args); | |
} | |
static int normalDirect(java.lang.invoke.MethodHandle mh, Object[] args) throws Throwable { | |
return (int)mh.invokeWithArguments(args[0], args[1]); | |
} | |
static int polyDirect(java.lang.invoke.MethodHandle mh, Object[] args) throws Throwable { | |
return (int)mh.invoke(args[0], args[1]); | |
} | |
public static int add(int a, int b) { return a+b; } | |
public static void main(String[] args) throws Throwable { | |
MethodHandle mh = MethodHandles.lookup().unreflect(Foo.class.getMethod("add", Integer.TYPE, Integer.TYPE)); | |
Object[] ints = { 1, 2 }; | |
System.out.println(normalDirect(mh, ints)); | |
System.out.println(normalArray(mh, ints)); | |
System.out.println(polyDirect(mh, ints)); | |
System.out.println(polyArray(mh, ints)); | |
} | |
} | |
/* | |
$ java Foo | |
3 | |
3 | |
3 | |
Exception in thread "main" java.lang.invoke.WrongMethodTypeException: cannot convert MethodHandle(int,int)int to (Object[])int | |
at java.base/java.lang.invoke.MethodHandle.asTypeUncached(MethodHandle.java:884) | |
at java.base/java.lang.invoke.MethodHandle.asType(MethodHandle.java:869) | |
at java.base/java.lang.invoke.Invokers.checkGenericType(Invokers.java:542) | |
at Foo.polyArray(Foo.java:9) | |
at Foo.main(Foo.java:26) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment