lombok works analysis

In the process of Lombok in use, only need to add the appropriate comments, do not need to write any code for this purpose. But the auto-generated code in the end is how to generate it?

The core is the place to comment on the resolution. JDK5 the introduction of notes, but also provides two analytical methods.

  • Parsing runtime

You can parse the annotations must be set @Retention runtime RUNTIME, so that you can get the annotation by reflection. java.lang, reflect reflection package provides an interface AnnotatedElement, the interface defines several methods to obtain information notes, Class, Constructor, Field, Method, Package and so implements the interface, the reflection will be very familiar friend should familiar with this analytical method.

  • Compile-time parsing

There are two mechanisms to resolve compile-time, respectively, under the simple description:

1)Annotation Processing Tool

Since JDK5 apt to produce, JDK7 been marked as expired, is not recommended for use in JDK8 has been completely removed from JDK6 start, you can replace it with Pluggable Annotation Processing API, apt to be replaced are mainly two reasons:

  • api in com.sun.mirror under non-standard package
  • Not integrated into javac, the need for additional run

2)Pluggable Annotation Processing API

JSR 269 from JDK6 added, as an alternative apt, and it solves two problems are apt, javac in the implementation of the program will call implementation of the API, so that we can make some enhancements to the compiler, then execute javac the process is as follows: 

 

On Lombok is essentially a realization of " JSR 269 API " program. In the process of using javac, which have an effect process is as follows:

  1. javac source code analysis, generates an abstract syntax tree (AST)
  2. During operation calls to achieve a "JSR 269 API" program of Lombok
  3. At this time, the respective tree node for AST Lombok on a first processing step is obtained, where to find the class @Data annotation corresponding syntax tree (AST), and then modify the syntax tree (AST), increased defines getter and setter methods
  4. javac using the modified abstract syntax tree (AST) generated bytecode file, that is, to add new class node (block)

Lombok have read the source code to achieve the corresponding annotations are HandleXXX, such as realized when HandleGetter.handle () @Getter annotations. There are other ways to achieve this using libraries, such as Google Auto , Dagger and so on.

 

 

Original: https: //www.cnblogs.com/heyonggang/p/8638374.html

 

 Disclaimer: This blog is a personal learning, as with other similar works, is purely coincidental, reproduced, please indicate the source!

Guess you like

Origin www.cnblogs.com/zhihuifan10/p/11325602.html