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?
我知道其他类型,如字符串: :new
,它可以使用 invokedynamic
指令指向String构造函数 java / lang / String。< init> ;(...)
,这只是一种具有特殊含义的方法。
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
编译器将数组构造函数引用 Foo [] :: new
转义为lambda( i - > new Foo [i]
),然后继续为w任何其他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屋!