Java Reference
In-Depth Information
Let's try to implement an instance of the Function interface using the old Java 7 syntax, as an
anonymous inner class, as shown in the following listing.
Listing D.1. A Function implemented as an anonymous inner class
import java.util.function.Function;
public class InnerClass {
Function<Object, String> f = new Function<Object, String>() {
@Override
public String apply(Object obj) {
return obj.toString();
}
};
}
Doing this, the corresponding generated bytecode for the Function created as an anonymous
inner class will be something along the lines of this:
0: aload_0
1: invokespecial #1
// Method java/lang/Object."<init>":()V
4: aload_0
5: new
#2
// class InnerClass$1
8: dup
9: aload_0
10: invokespecial #3
// Method InnerClass$1."<init>":(LInnerClass;)V
13: putfield
#4
// Field f:Ljava/util/function/Function;
16: return
This code shows the following:
An object of type InnerClass$1 is instantiated using the bytecode operation new . A reference to the
newly created object is pushed on the stack at the same time.
The operation dup duplicates that reference on the stack.
This value then gets consumed by the instruction invokespecial , which initializes the object.
The top of the stack now still contains a reference to the object, which is stored in the f1 field of the
LambdaBytecode class using the putfield instruction.
InnerClass$1 is the name generated by the compiler for the anonymous class. If you want to
reassure yourself, you can inspect the InnerClass$1 class file as well, and you'll find the code for
the implementation of the Function interface:
 
Search WWH ::




Custom Search