Java 调用方法时执行装箱
为什么方法句柄不执行基元类型的装箱Java 调用方法时执行装箱,java,methods,boxing,Java,Methods,Boxing,为什么方法句柄不执行基元类型的装箱 /* 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 publi
/* 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) 自动装箱/取消装箱在编译和运行时非常方便,它隐藏了primative int和class Integer不同的事实。您对该方法的查找是寻找一个名为“i”的方法,该方法返回一个primative int并具有两个primative int参数。事实并非如此。因此,将查找更改为与函数声明匹配的:
MethodType mt = MethodType.methodType(int.class, int.class, Integer.class);
MethodHandle mh = lu.findStatic(Ideone.class, "i", mt);
错误是
IllegalAccessException:符号引用类不是公共的
,这是可以理解的:publicLookup
只能查找。。。公共类(如javadoc中所述),但您的类没有公共修饰符。切换到public class Ideone
,您将更进一步。顺便说一句:说出你的错误总是好的,而不仅仅是“它抛出了一个异常”。