Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do Java 8 array constructor references work?

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?

like image 870
Clashsoft Avatar asked Apr 04 '15 14:04

Clashsoft


People also ask

Is constructor reference allowed in Java 8?

A method reference can also be applicable to constructors in Java 8. A constructor reference can be created using the class name and a new keyword. The constructor reference can be assigned to any functional interface reference that defines a method compatible with the constructor.

How does method reference work in Java 8?

Java provides a new feature called method reference in Java 8. Method reference is used to refer method of functional interface. It is compact and easy form of lambda expression. Each time when you are using lambda expression to just referring a method, you can replace your lambda expression with method reference.

What is constructor reference in Java?

Constructor Reference is used to refer to a constructor without instantiating the named class. The Constructor reference mechanism is yet another game changing addition by Java 8. You can pass references to constructors as arguments or assign to a target type.

What is method reference and constructor references in Java 8?

Java 8Object Oriented ProgrammingProgramming. A method reference is similar to lambda expression used to refer a method without invoking it while constructor reference used to refer to the constructor without instantiating the named class. A method reference requires a target type similar to lambda expressions.


1 Answers

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

like image 145
Brian Goetz Avatar answered Sep 16 '22 14:09

Brian Goetz