2

This strange behavior allows you to call methods with the wrong type

For example:

static void test(Integer v) {
    System.out.println("test " + (Object)v);
}

MethodHandle test = MethodHandles.lookup().findStatic(/*this class*/, "test",
                MethodType.methodType(void.class, Integer.class));

MethodHandle i1 = MethodHandles.invoker(MethodType.methodType(void.class, Integer.class));
MethodHandle i2 = MethodHandles.invoker(MethodType.methodType(void.class, MethodHandle.class, String.class));
i2.invoke(i1, test, "string");

prints "test string"

All versions of android 8.0+ behave like this. I was expecting an error while checking the call type.

PS. After some experiments, I did this:

MethodHandle test = MethodHandles.identity(String.class);
MethodHandle i1 = MethodHandles.invoker(MethodType.methodType(String.class, String.class));
MethodHandle i2 = MethodHandles.invoker(MethodType.methodType(Integer.class, MethodHandle.class, String.class));

Integer tmp = (Integer) i2.invokeExact(i1, test, "string");
System.out.println(tmp);

prints "string"

WTF?

Vladimir
  • 21
  • 3
  • I found something interesting here https://android.googlesource.com/platform/libcore/+/refs/heads/master/ojluni/src/main/java/java/lang/invoke/Transformers.java It looks like the answer is incorrect behavior of the invokeFromTransform method – Vladimir May 26 '23 at 17:57
  • It just calls transform on all Transformers without checks – Vladimir May 26 '23 at 18:08

0 Answers0