How do Java 8 array constructor references work?

JavaArraysJava 8Method Reference

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionClashsoftView Question on Stackoverflow
Solution 1 - JavaBrian GoetzView Answer on Stackoverflow