Home > Java > javaTutorial > How to read Lambda source code in Java

How to read Lambda source code in Java

王林
Release: 2023-05-13 11:10:06
forward
1445 people have browsed it

How to read Lambda source code in Java


1. Demo

First we look at a demo of Lambda expression, as shown below:

How to read Lambda source code in Java

The code is relatively simple, just start a new thread and print a sentence, but for the picture () -> System.out.println (“ lambda is run “) this It is estimated that many students are confused about this kind of code. How does Java identify this kind of code?

If we change the writing method to anonymous inner class, it will be very clear and everyone can understand it, as shown below:

How to read Lambda source code in Java

Does that mean () -> System.out.println (“ lambda is run “) Does this form of code actually create an inner class? In fact, this is the simplest Lambda expression. We cannot see the source code and its underlying structure through IDEA. Here we will introduce several ways to see its underlying implementation.

2. Exception judgment method

We can actively throw exceptions during code execution and print out the stack. The stack will explain its running trajectory. Generally, this method is simple and efficient, and you can basically see Let’s try the hidden code in many cases, as shown below:

How to read Lambda source code in Java

From the exception stack, we can see that the JVM automatically creates an internal class for the current class ($ appearing multiple times in the error stack indicates an internal class). During the execution of the code of the internal class, an exception is thrown, but the code shown here is Unknown Source, so we cannot debug it. Under normal circumstances, exceptions Both can expose the code execution path, and we can set breakpoints and run again. However, for Lambda expressions, through the exception judgment method, we only know that there are internal classes, but we cannot see the source code in the internal classes.

3. javap command method

javap is a tool that comes with Java to view class bytecode files. Computers that have installed the Java basic environment can directly execute the javap command, as shown below:

How to read Lambda source code in Java

Among the command options, we mainly use the -v -verbose command to completely output the contents of the bytecode file.

Next we use the javap command to view the Lambda.class file. During the explanation, we will bring some knowledge about class files.

We find the location of Lambda.class in the command window, execute the command: javap -verbose Lambda.class, and then you will see a long list of things, these are called assembly instructions, let’s do it next Let me explain (all reference materials come from the Java Virtual Machine Specification, no one-by-one citation is required):

In the assembly instructions, we can easily find a long list of types starting with Constant pool, which we call the constant pool. Official It is called Run-Time Constant Pool in English. We simply understand it as a table filled with constants. The table contains clear numbers and text at compile time, type information of classes, methods and fields, etc. Each element in the table is called cpinfo. cpinfo consists of a unique identification (tag) name. Currently, there are a total of tag types:

How to read Lambda source code in Java

Post Here is part of the picture we parsed:

How to read Lambda source code in Java

  1. The words "Constant pool" in the picture represent that the current information is a constant pool;

  2. Each row is a cp_info, #1 in the first column represents the position marked as 1 in the constant pool;

  3. The second in each row Column is the unique identifier (tag) of cp_info. For example, Methodref corresponds to CONSTANT_Methodref in the above table (the value in the table above corresponds to the tag of 10), which means that the current row represents the description information of the method. , such as the name of the method, input parameter type, output parameter type, etc. The specific meaning can be found in the Java virtual machine specification. The screenshot of Methodref is as follows:
    How to read Lambda source code in Java

  4. In the third column of each row, if it is a specific value, the specific value will be displayed directly. If it is a complex value, the reference to cp_info will be displayed, for example, marked red 2 in the picture, Reference two cp_info at positions 13 and 14. 13 indicates that the method name is init, and 14 indicates that the method has no return value. The combination of the name and return type of the method indicates a parameterless constructor;

  5. The fourth column of each row is the specific value.

For the more important cp_info type, we explain its meaning:

  1. InvokeDynamic represents the dynamic calling method, which we will explain in detail later;

  2. Fieldref represents the description information of the field, such as the name and type of the field;

  3. NameAndType is a description of the field and method type;

  4. MethodHandle method handle, the general name for dynamically calling methods, we don’t know the specific one at compile time That method, but you will definitely know which method is called when running;

  5. MethodType dynamic method type, you will only know what its method type is when running dynamically.

From the three places marked in red in the above figure, we found Ljava/lang/invoke/MethodHandles$Lookup, java/lang/invoke/LambdaMetafactory.metafactory similar to this code, MethodHandles and LambdaMetafactory is an important method under the java.lang.invoke package. The invoke package mainly implements the functions of dynamic languages. We know that the Java language is a static compiled language. During compilation, the types of classes, methods, fields, etc. have been determined. , and invoke implements a dynamic language, which means that the types of classes, methods, and fields are not known when compiling, and are only known when running.

For example, this line of code: Runnable runnable = () -> System.out.println(“lambda is run”); When the compiler compiles (), the compiler does not know what this bracket does. , only when running will you know that this represents the Runnable.run() method. Many classes in the invoke package are designed to represent these (), which we call method handles (MethodHandler). When compiling, the compiler only knows that this is a method handle, and does not know what method is actually executed. I didn't know it until the time, so the question is, when the JVM executes, how does it know that the () method handle actually executes the Runnable.run() method?

First, let’s take a look at the assembly instructions of the simple method:

How to read Lambda source code in Java

From the above figure, we can see the () -> System in the simple method. The () in the out.println(“lambda is run”) code is actually the Runnable.run method.

We trace back to the #2 constant pool, which is marked red 1 in the above picture. InvokeDynamic indicates that this is a dynamic call. The call is the cp_info of the two constant pools. The position is #0:#37. We Look down for #37, which means // run:()Ljava/lang/Runnable. This indicates that when the JVM is actually executed, the Runnable.run() method needs to be called dynamically. From the assembly instructions, we can see that () In fact, it is Runnable.run(). Let’s debug below to prove it.

We found the words LambdaMetafactory.metafactory in 3 places in the above picture. By querying the official documentation, we learned that this method is the key to linking to the real code during execution, so we typed it in the metafactory method. Debug with a breakpoint, as shown below:

How to read Lambda source code in Java

metafactory method input parameter caller represents the location where the dynamic call actually occurs, invokedName represents the name of the calling method, and invokedType represents the multiple inputs of the call. Parameters and output parameters, samMethodType represents the parameters of the specific implementer, implMethod represents the actual implementer, and instantiatedMethodType is equivalent to implMethod.

To summarize the above:

1: From the simple method of the assembly instruction, we can see that the Runnable.run method will be executed;

2: In the actual operation When the JVM encounters the invokedynamic instruction of the simple method, it will dynamically call the LambdaMetafactory.metafactory method and execute the specific Runnable.run method.

So the specific execution of the Lambda expression value can be attributed to the invokedynamic JVM instruction. It is precisely because of this instruction that although you don’t know what to do when compiling, you can find the specific execution when running dynamically. code.

Then let’s take a look at the end of the assembly instruction output. We found the internal class found in the exception judgment method, as shown below:

How to read Lambda source code in Java

In the above picture There are many arrows, and all the information of the current internal class is clearly expressed layer by layer.

The above is the detailed content of How to read Lambda source code in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template