Lombok
All of the following annotation operations can be done with this command: MVN compile Look at the compiled bytecode and you will see how Lombok changes with annotations
Lombok plugin IDEA is installed
What is a lombok
Liverpoolfc.tv: projectlombok.org/
An excellent Java code library that simplifies Java coding and provides a way to simplify Java code
Lombok eliminates Java’s verbose code, especially for simple Java objects, by adding annotations
use
Step1: add pom dependencies
< the dependency > < groupId > org. Projectlombok < / groupId > < artifactId > lombok < / artifactId > < version > 1.18.16 < / version > <scope>provided</scope> </dependency> <! - https://mvnrepository.com/artifact/org.projectlombok/lombok/1.18.16-- > <! --scope=provided, indicating that it only takes effect at compile time and does not need to be typed into the package. Lombok interprets Lombok annotated Java files as full Class files at compile time.Copy the code
Step2: add IDE tool support for Lombok
Click the File-Settings Settings screen to install the Lombok plug-in and restart the IDE
Step3: Need to enable annotation Processors in the Settings and restart IDEA
The Lombok plug-in annotates the Set/Get methods
Common annotations
@Getter/@Setter/@Data
Generate getter/setter methods for all member variables on a function class
Function on a member variable to generate a getter/setter method for that member variable
You can view bytecode MVN compile by compiling
Further control
Method controls access levels and does not generate set or GET methods
@setter @getter public class User {/** * do not want to generate get method */ @getter (accesslevel.none) private int id; /** * access control */ @getter (accesslevel.protected) private String name; Private Final String DEMONAME = "DEMONAME "; static Date createTime = new Date(); Private static final String ADDRESS = "下 载 "; }Copy the code
NonNull+ constructor annotation ArgsConstructor for combat
Old-fashioned parameter check
Public void login(String PWD){// Verify if(PWD! = null){ //TODO }else { throw new NullPointerException(); }}Copy the code
NonNull parameter verification
Adds logic validation to the bytecode at compile time
Public void login(String PWD){// Verify if(PWD! = null){ //TODO }else { throw new NullPointerException(); }}Copy the code
Generates an empty constructor
Generates all parameter constructors
@noargsconstructor // Generate null constructors @allargsconstructor // Generate constructors for all arguments (not final or static)Copy the code
Specifies the constructor for the argument
2) @NoargsConstrucotr does not work on a classCopy the code
Lombok plugin for contrast reflection technology
Plug-in annotation
JSR 269 plug-in annotation processing
JSR 269:Pluggable Annotation Processing API implements the "Annotation Processor" to preprocess custom annotations during the JavAC compilation phase. https://www.jcp.org/en/jsr/detail?id=269Copy the code
The popular science
JSR stands for Java Specification Requests. A Java Specification proposal is a formal request to add a standardized technical Specification to the JCP (Java Community Process). Anyone can submit a JSR, To add new apis and services to the Java platform. JSR has become an important standard in the Java worldCopy the code
Lombok parses the process
After Javac parses into an AST abstract syntax tree, Lombok writes its own annotation processor, Dynamically modify the AST to add new nodes (that is, the code generated for Lombok's custom annotations), resulting in a JVM executable bytecode Class file that you can see compiled in the target directoryCopy the code
Reflection technique contrast
There is also a reflection technique that can achieve this effect. How do the two compare?
Custom annotations using Annotation Processing are modified at compile time. JDK reflection is modified dynamically at run time. Conclusion: Reflection is more flexible but carries a higher performance costCopy the code
Lombok’s toString() annotation
Why would a Javabean object override the toString() annotation?
- Lists and other collections are inconvenient to debug
- Console or log output object, which prints memory addresses by default
🌰
UserDO userDO = new UserDO(); userDO.setAge(11); System.out.println(userDO); Com / / output information. Keep. Shop. Model. UserDO @ 1677 d1Copy the code
@ToString
1. Applied to classes, overriding the default toString() method
2. A field is not included
@ToString(exclude = {"age"})
Copy the code
3. Only one field is displayed
@ToString(of = {"name"})
Copy the code
Hashcode and equal methods
Why do objects override the hashcode and equal methods?
HashCode methods
A method of the top-level Object class, all classes that inherit from Object, returns an int
According to certain hash rules (store address, field, or length, etc.), map to a value, that is, a hash value
The Equals method
A method of the top-level Object class, all classes that inherit Object, returns a Boolean type
The general logic is as follows to match whether two objects are the same according to a user-defined matching rule
// Check if the address is the same // check if the class type is not null // check if the fields in the object match one by oneCopy the code
parsing
If two objects are equal, their hashcode() value must be the same. (Equality here means that equals() returns true when comparing two objects.) If two objects are hashcode equal, they are not necessarily equal. In a hash table hashCode() is equal, that is, the hashes of two key-value pairs are equal. And then the hash values are equal, and it's not always true that the key value pairs are equal, so that's what's called a hash conflict scenario, and you need to check equals to see if the objects are equalCopy the code
Application scenarios
🌰 : When inserting an object into a collection, how do you determine whether the object already exists in the collection? For example, Set ensures that the stored object is unique and determines whether it is the same object?
So the Set object must override two methods to determine whether the two objects are the same. First check whether the inserted hashCode of obj exists. If hashCode doesn't exist, insert the set value and then check equals to see if the objects are equalCopy the code
class User { private int age; private String name; private Date time; @override public Boolean equals(Object o) {if (this == o) return true; if (o == null || getClass() ! = o.getClass()) return false; Student student = (Student) o; return age == student.age && Objects.equals(name, student.name) && Objects.equals(time, student.time); } @Override public int hashCode() { return Objects.hash(age, name, time); }}Copy the code
Object matches the EquealsAndHashCode annotation
@EqualsAndHashCode
Class, overriding the default equals and hashCode, on all attributes
- An attribute is not included
@EqualsAndHashCode(exclude = {"age"})
Copy the code
- Only one property is output
@EqualsAndHashCode(of = {"name"})
Copy the code
The Lombok plug-in multi-annotation collection configures Data
Lombok explained so many annotations above, it’s too much trouble to add one by one 🐴
@Data
Define a clean class, define on the class, add this annotation (the above annotations can be removed without use) MVN compile to view the effect of the bytecode
(However, the annotation does not generate a parameter constructor.)
@Data
public class User {
private int id;
}
Copy the code
Builder pattern and Lombok annotation @Builder
Lombok already gets and sets for you. Do you still assign objects one by one when you use them?
For example, do the following
public static void main(String[] args) { User user = new User(); user.setId(1); User.setname (" outlaw fanatic: Zhang SAN "); }Copy the code
Builder model
Otherwise known as the Builder pattern
Scenario: Consider using the Builder pattern when a bean class overloads multiple constructors and the parameters are used randomly
The Builder pattern is used for javabean assignments produced by Google’s open source Protobuf protocol
@ Builder annotations
@builder@data public class User {} @builder@data public class User {} @builder@data public class User {} @builder@data public class User {} @builder@data public class User {} @builder@data public class User {} @builder@data public class User {} System.out.println(user);Copy the code
Log printing is more convenient -@Log- @slf4j
@Log/@Slf4j
Class to generate a log variable for logging
If it doesn’t work, check the Lombok plug-in
To print the original log, we need to write a line of Logger
private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
Copy the code
use
@slf4j public class UserServiceImpl {public void getUser(String name){try {//TODO log.info(" user login name: {}",name); }catch (Exception e){ log.error("UserServiceImpl.getUser error! name: {}"+name,e); }}}Copy the code
Note: Be sure to print the entire stack when printing the error log, depending on which overloaded method is called
The error method is the way I wrote it up here, but it doesn’t work if you change the + to a comma
public void error(String msg, Throwable t);
Copy the code
Annotations are common in Lombok
annotations | Effect of the column | describe |
---|---|---|
@Getter/@Setter | Class/variable | Generate getter/setter methods for variables |
@NonNull | The ginseng | Parameter non-null check |
@NoArgsConstructor | class | Generates an empty constructor |
@AllArgsConstructor | class | Generates all parameter constructors |
@RequiredArgsConstructor | class | Specifies the argument generation constructor |
@ToString | class | Override the toString() method |
@EqualsAndHashCode | class | Override hashCode and equals methods |
@Data | class | A collection of annotations |
@Builder | class | Bean assignment |
@Log/@Slf4j | class | Log print |
Advantages and disadvantages of Lombok usage scenarios
disadvantages
- Use requirements Make sure that the plug-in is installed in the IDE, and if one person on the project team uses it, everyone uses it
- Code readability, low debuggability, for example, if you want to know that the getter method of a property in a class is referenced by those classes, but you can’t see it
- This affects upgrades if you upgrade to a newer version of the JDK if features are not supported in Lombok
- Pay attention to common details
For example, if @data is used instead of @equalSandHashCode (callSuper=true), the default is @equalSandHashCode (callSuper=false), and the generated equals() method only compares the attributes of subclasses, Attributes inherited from the parent class are not considered. Regardless of whether the access to the attributes of the parent class is open or not, as long as you know whether you need to use the attributes of the parent class, you can also provide customized configuration, so don't worry too muchCopy the code
advantages
- Use annotations to help generate code automatically
- Greatly reduces the amount of code, making the code very brief
- Partial annotations can be developed in business projects to improve efficiency
Should it be used in a project?
It is not recommended for use in projects where middleware is being developed. Middleware design requirements require decoupling to reduce dependency ** (high cohesion, low coupling) **
The business Item entity class can be used and used with knowledge of the corresponding common annotation principles
Feel good big guy dot a thumbs up bai, hand knock screenshot demo is not easy