Java 8 数组构造函数引用如何工作? [英] How do Java 8 array constructor references work?
问题描述
假设我们有一个 IntFunction
类型的变量,它返回一个整数数组:
Say we have a variable of type IntFunction
that returns an integer array:
IntFunction<int[]> i;
使用 Java 8 泛型,可以使用这样的构造函数引用来初始化这个变量:
With Java 8 generics, it is possible to initialize this variable with a constructor reference like this:
i = int[]::new
Java 编译器如何将其转换为字节码?
How does the Java compiler translate this to bytecode?
我知道对于其他类型,例如 String::new
,它可以使用一个 invokedynamic
指令指向 String 构造函数 java/lang/String.
,这只是一个有特殊意义的方法.
I know that for other types, like String::new
, it can use an invokedynamic
instruction that points to the String constructor java/lang/String.<init>(...)
, which is just a method with a special meaning.
这对数组是如何工作的,看到有构造数组的特殊说明?
How does this work with arrays, seeing that there are special instructions for constructing arrays?
推荐答案
你可以通过反编译java字节码来找出自己:
You can find out yourself by decompiling the java bytecode:
javap -c -v -p MyClass.class
编译器 desugars 数组构造函数将 Foo[]::new
引用到一个 lambda (i -> new Foo[i]
),然后像任何其他 lambda 或方法参考.这是这个合成 lambda 的反汇编字节码:
The compiler desugars array constructor references Foo[]::new
to a lambda (i -> new Foo[i]
), and then proceeds as with any other lambda or method reference. Here's the disassembled bytecode of this synthetic lambda:
private static java.lang.Object lambda$MR$new$new$635084e0$1(int);
descriptor: (I)Ljava/lang/Object;
flags: ACC_PRIVATE, ACC_STATIC, ACC_SYNTHETIC
Code:
stack=1, locals=1, args_size=1
0: iload_0
1: anewarray #6 // class java/lang/String
4: areturn
(它的返回类型是Object,因为IntFunction中擦除的返回类型是Object.)
(It's return type is Object because the erased return type in IntFunction is Object.)
这篇关于Java 8 数组构造函数引用如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!