android doesn't check called MethodHandle type in java.lang.invoke.Transformers

54 Views Asked by At

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?

0

There are 0 best solutions below