[英]Performing boxing when invoking method
为什么方法处理程序不执行基本类型的装箱?
/* 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)您的课程不是public,这是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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.