为什么方法句柄不执行基本类型的装箱?
/* package whatever; // don't place package name! */
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static int i(int i1, Integer i2){
return i1 + i2;
}
public static void tm() throws Throwable {
MethodHandles.Lookup lu = MethodHandles.publicLookup();
MethodType mt = MethodType.methodType(int.class, int.class, int.class);
MethodHandle mh = lu.findStatic(Ideone.class, "i", mt);
System.out.println(mh.invoke(1, 2));
}
public static void main(String[] args) throws Throwable {
tm();
}
}
这是我尝试过的代码。它抛出异常。我期望 MethodHandle::invoke
而不是 invokeExact
执行 asType
调整,包括装箱转换。怎么了?
最佳答案
这里有两个问题:
1) 你的类不是 publicLookup() 所要求的。因此,将您的类声明更改为:
public class Ideone
{
2) 自动装箱/拆箱在编译和运行时很方便,它隐藏了原始 int 和类 Integer 不同的事实。您对该方法的查找是寻找一个名为“i”的方法,该方法返回一个原始 int 并具有两个原始 int 参数。事实并非如此。因此,将您的查找更改为此,它与函数声明匹配:
MethodType mt = MethodType.methodType(int.class, int.class, Integer.class);
MethodHandle mh = lu.findStatic(Ideone.class, "i", mt);
关于java - 调用方法时进行装箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49255396/