Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to install and use Lombok of Java

2025-02-22 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how to install and use Java Lombok, which has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, let the editor take you to know about it.

Installation

The installation of Lombok is divided into two parts: the installation of the Idea plug-in and the import of pom files in maven.

Installation of the Idea plug-in

Click Settings, select the plug-in, search for Lombok (requires networking) in the plug-in configuration of Idea or download the local installation on the official website, and click initialize the installation.

You can also see the annotations that it supports in the description of the plug-in.

Import of pom File in maven

The second step is to introduce dependencies in pom, the current smallest version 1.18.10.

Org.projectlombok lombok 1.18.10

If you are creating a Spring Boot project through Idea, you can select Lombok directly in "Developer Tool" when you create the project.

After completing the above two steps, you can use the artifact in your code.

Use

This is the supported comment on the official website, and we can also check it here: https://projectlombok.org/features/all

Common notes and their introductions are given here:

Val

Use val as the type declared by the local variable instead of actually writing the type. When you do this, the type is inferred from the initialization expression.

Public Map getMap () {val map = new HashMap (); map.put ("1", "a"); return map;}

The effect is as follows:

Public Map getMap () {HashMap map = new HashMap (); map.put ("1", "a"); return map;}

In other words, in local variables, Lombok can help you infer specific types, but can only be used in local variables.

@ Data

One of the most commonly used annotations for @ Data. Note on the class, providing getter/setter methods for all the properties of the class, as well as equals, canEqual, hashCode, toString methods.

That is, developers do not have to write the corresponding methods by hand, and Lombok will help you generate all of the above methods.

The example of using @ Data is as follows, and the most intuitive thing is that you don't have to write the getter/setter method.

@ Datapublic class Demo {private int id; private String remark;}

Let's see what this class looks like after compilation.

Public class Demo {private int id; private String remark; public Demo () {} public int getId () {return this.id; public String getRemark () {return this.remark; public void setId (final int id) {this.id = id; public void setRemark (final String remark) {this.remark = remark Public boolean equals (final Object o) {if (o = = this) {return true;} else if (! (o instanceof Demo)) {return false;} else {Demo other = (Demo) o; if (! other.canEqual (this)) {return false } else if (this.getId ()! = other.getId ()) {} else {Object this$remark = this.getRemark (); Object other$remark = other.getRemark (); if (this$remark = = null) {if (other$remark! = null) {return false }} else if (! this$remark.equals (other$remark)) {return false;} return true;}} protected boolean canEqual (final Object other) {return other instanceof Demo; public int hashCode () {int PRIME = true; int result = 1 Int result = result * 59 this.getId (); Object $remark= this.getRemark (); result = result * 59 ($remark= = null? 43: $remark.hashCode ()); return result; public String toString () {return "Demo (id=" this.getId () ", remark=" this.getRemark () ")";}

The official website is more detailed, and only part of it is shown here. For example, the following figure is an example given on the official website:

Link: https://projectlombok.org/features/Data

@ Getter/@Setter

Acts on a property to provide a getter/setter method for that property

Function and class, for all the properties of the class to provide getter/setter methods, all provide default constructors.

An example of using @ Getter/@Setter is as follows:

Public class GetterSetterExample {@ Getter @ Setter private int age = 10; @ Setter (AccessLevel.PROTECTED) private String name; @ Override public String toString () {return String.format ("% s (age:% d)", name, age);}}

It looks like this after compilation:

Public class GetterSetterExample {private int age = 10; private String name; @ Override public String toString () {return String.format ("% s (age:% d)", name, age);} public int getAge () {return age; public void setAge (int age) {this.age = age; protected void setName (String name) {this.name = name;}

The rest of the examples will not be shown, you can go to the official website to check the details, here only give the role.

@ Log4j

Acts on the class, providing the class with a log4j log object with the property name log.

@ Log4jpublic class Demo {}

This attribute is generally used in Controller, Service and other business processing classes. The same with this annotation is @ Log4j2, as the name implies, for Log4j2.

@ AllArgsConstructor

Acts on the class, providing a constructor that contains all parameters for the class. Note that the default constructor is not provided at this time.

@ AllArgsConstructorpublic class Demo {private int id; private String remark;}

The effect is as follows:

Public class Demo {private int id; private String remark; public Demo (final int id, final String remark) {this.id = id; this.remark = remark;}} @ NoArgsConstructor

Acts on the class to provide a no-parameter constructor.

You can use it with @ AllArgsConstructor, and two construction methods are generated: the no-parameter construction method and the all-parameter construction method.

@ EqualsAndHashCode

Act on the class to generate equals, canEqual, hashCode methods.

For specific results, please see the initial @ Data effect, or refer to the official website.

@ NonNull

Acts on a property, providing a non-null check for this parameter, and throwing a null pointer exception if the parameter is empty.

How to use it:

Public class Demo {@ NonNull private int id; private String remark;} @ RequiredArgsConstructor

Acts on a class, generating constructors from all member variables in the class with @ NonNull annotations or final modifiers as parameters.

@ Cleanup

Act on the variable to ensure that the resource represented by the variable is automatically closed. The close () method of the resource is called by default. If the resource has other closing methods, it can be specified with @ Cleanup ("methodName").

Public void jedisExample (String [] args) {try {@ Cleanup Jedis jedis = redisService.getJedis ();} catch (Exception ex) {logger.error ("Jedis exception:", ex)}}

The effect is equivalent to:

Public void jedisExample (String [] args) {Jedis jedis= null; try {jedis= redisService.getJedis ();} catch (Exception e) {logger.error ("Jedis exception:", ex)} finally {if (jedis! = null) {try {jedis.close ();} catch (Exception e) {e.printStackTrace () } @ ToString

Acts on the class to generate a toString method that contains all the parameters. See the toString method in @ Data.

@ Value

Acting on a class generates full-parameter constructors, getter methods, equals, hashCode, and toString methods.

Compared with @ Data, there are more full-parameter constructors and fewer default constructors, setter methods, and canEqual methods.

It should be noted that the field will be decorated with final. I feel a little out of control here and it is not recommended to use it.

@ SneakyThrows

Acting on the method, it is equivalent to adding a try-catch handle to the code in the method, and using Lombok.sneakyThrow (e) to throw the exception in the catch that catches the exception. Use @ SneakyThrows (BizException.class) to specify that a specific exception is thrown.

@ SneakyThrowspublic int getValue () {int a = 1; int b = 0; return a hand b;}

The effect is as follows:

Public int getValue () {try {int a = 1; int b = 0; return a / b;} catch (Throwable var3) {throw var3;}} @ Synchronized

Acting on class methods or instance methods has the same effect as synchronized.

The difference is that the lock object is different. For class method and instance method, the lock object of the synchronized keyword is the class object and this object of the class, while the lock object of @ Synchronized is the private static final object lock and the private final object lock. You can also specify a lock object.

Public class FooExample {private final Object readLock = new Object (); @ Synchronized public static void hello () {System.out.println ("world");} @ Synchronized ("readLock") public void foo () {System.out.println ("bar");}}

The effect is as follows:

Public class FooExample {private static final Object $LOCK = new Object [0]; private final Object readLock = new Object (); public static void hello () {synchronized ($LOCK) {System.out.println ("world");}} public void foo () {synchronized (readLock) {System.out.println ("bar");}} @ Builder

Acting on classes, if you like to use Builder's streaming operations, then @ Builder may be your favorite annotation.

How to use it:

@ Builderpublic class Demo {private int id; private String remark;}

The effect is as follows:

Public class Demo {private int id; private String remark; Demo (final int id, final String remark) {this.id = id; this.remark = remark;} public static Demo.DemoBuilder builder () {return new Demo.DemoBuilder (); public static class DemoBuilder {private int id; private String remark DemoBuilder () {} public Demo.DemoBuilder id (final int id) {this.id = id; return this; public Demo.DemoBuilder remark (final String remark) {this.remark = remark; public Demo build () {return new Demo (this.id, this.remark) Public String toString () {return "Demo.DemoBuilder (id=" this.id ", remark=" this.remark ")";}

We can see that the DemoBuilder class is provided inside the class to handle specific streaming operations. At the same time, the construction method of the whole parameter is provided.

Thank you for reading this article carefully. I hope the article "how to install and use Java Lombok" shared by the editor will be helpful to everyone. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report