Summary of Java skills: How to read Lambda source code
This article brings you relevant knowledge about java, which mainly introduces related issues about how to view Lambda source code. Using Lambda expressions can perform a large number of optimizations on the code. Use several You can do a lot of things with just one line of code. Let’s take a look at it. I hope it will be helpful to everyone.
Recommended study: "java Video Tutorial"
Everyone knows that Lambda expressions are added in Java8, use Lambda expressions The formula can optimize the code a lot, and you can do a lot of things with just a few lines of code. This chapter takes Lambda as an example. The first section explains its underlying execution principle, and the second section explains the common postures of Lambda flow in work.
1. Demo
First we look at a demo of Lambda expression, as shown below:
The code is relatively simple, just start a new thread to print a sentence, but for the code in the picture () -> System.out.println (“ lambda is run “), I think many students are confused. How does Java Do you recognize this code?
If we change the writing method to anonymous inner class, it will be very clear and everyone can understand it, as shown below:
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:
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 that can view class bytecode files. Computers that have installed the Java basic environment can directly execute the javap command, as shown below:
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, and will not be cited one by one):
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:
Post Here is part of the picture we parsed:
The words "Constant pool" in the picture represent that the current information is a constant pool;
-
Each row is a
cp_info
, #1 in the first column represents the position marked 1 in the constant pool; The second column of each row 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 10 tag), which means that the current line 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: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,
cp_info will be displayed. The reference of
, for example, marked red 2 in the picture, refers to the twocp_info
at positions 13 and 14. 13 means that the method name is init, 14 means that the method has no return value, and the combination represents the name of the method. And the return type is a parameterless constructor;The fourth column of each row is the specific value.
For the more important cp_info type, we explain its meaning:
- InvokeDynamic represents a dynamic calling method, which we will explain in detail later;
- Fieldref represents the description information of the field, such as the name and type of the field;
- NameAndType is the description of the field and method type;
- MethodHandle method handle, the collective name for dynamic calling methods, during compilation We don't know which method is specific at the time, but we will definitely know which method is being called at runtime;
- MethodType is a dynamic method type, and we will only know what its method type is when running dynamically.
We found code similar to this in Ljava/lang/invoke/MethodHandles$Lookup, java/lang/invoke/LambdaMetafactory.metafactory from the three places marked in red in the above figure, both MethodHandles and LambdaMetafactory Important methods 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:
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:
The 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.
Next, 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:
There are many arrows in the above picture. All the information of the current internal class is expressed clearly layer by layer.
4. Summary
Let us summarize, Lambda expression execution mainly relies on the JVM instruction of invokedynamic. The full path of the class we demonstrate is: demo.eight.Lambda. Interested Students can try it themselves.
Without further ado, the article is over, looking forward to the third series!
Recommended study: "java video tutorial"
The above is the detailed content of Summary of Java skills: How to read Lambda source code. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
