Say we have a variable of type IntFunction
that returns an integer array:
IntFunction<int[]> i;
With Java 8 generics, it is possible to initialize this variable with a constructor reference like this:
i = int[]::new
How does the Java compiler translate this to bytecode?
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?
You can find out yourself by decompiling the java bytecode:
javap -c -v -p MyClass.class
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
(It's return type is Object because the erased return type in IntFunction is Object.)
来源:https://stackoverflow.com/questions/29447561/how-do-java-8-array-constructor-references-work