preface

Lombok is a Java development plug-in that allows Java developers to define annotations to eliminate redundant code in business processes, particularly simple Java model objects (POJOs). By using Lombok to develop the plug-in in a development environment, you can save yourself a lot of time by repeatedly building methods like hashCode and Equals and accessor and ToString for various business object models. For these methods, it can automatically help us produce them during compilation of the source code without degrading the performance of the program as reflection does. This article will take you through the use and principles of Lombok.

Public account: “Asanha’s IT Hut”

1. Lombok’s concept

“Concept:”

  • Lombok is a Java utility that helps developers eliminate redundant code through annotations for simple Java objects (POJOs).

2. Lombok installation

“Installation Steps:”

  • Search for Lombok in Plugins for IDEA

  • Lombok installation

“Attention:”

  • Remember to import Lombok. Jar into your Project when using Lombok annotations. For Maven Project, add dependencies to POM.xml

    Org. Projectlombok lombok 1.16.8

3. Lombok notes

“Common notes:”

Lombok notes * val: used before a local variable to declare it final* @nonnull: NullPointerException: this annotation will automatically check whether the method is null. If null, throw NPE (NullPointerException) * @cleanup: Automatically manages resources before local variables, cleans up resources before exiting within the current variable scope, automatically generates try-finally code to close streams * @getter / @setter: Instead of writing your own setters and getters, you can specify an access range * @toString: ToString(exclude= "id"); toString (exclude= "id"); toString (exclude= "id") Or @toString (callSuper=true, includeFieldNames=true) calls the ToString method of the parent class, containing all attributes * @equalSandHashCode: Use this class to automatically generate equals and hashCode methods * @noargsconstructor, @requiredargsconstructor and @allargsconstructor: For classes, automatically generate constructors that take no arguments and all arguments, and constructors that take all @nonNULL attributes as arguments. Specifying staticName = "of" also generates a static factory method that returns the class object, which is much more convenient than using the constructor * @data: Annotation, which is the class equivalent of using @ToString, @EqualSandhashCode, @getter, @setter, and @RequiredargsConstrutor at the same time, is a very useful construtor for POJO classes. * @Value: When used with classes, it is the immutable form of @data, equivalent to adding a final declaration to a property, providing only getters but no setters * @builder: For classes, constructors, and methods, providing you with the complex Builder APIs, Lets you call Person.builder().name("Adam Savage").city("San Francisco").Job ("Mythbusters").job("Unchained ") Reaction").build(); See Builder* @sneakythrows: automatically throws checked exceptions without explicitly using the throws statement * @synchronized on methods: $lock = $lock; $lock = $lock; $lock = $lock; $lock = $lock; That is, you cannot prevent uncontrolled code from locking this or class objects, which may cause race conditions or other thread errors. Generate different types of log objects based on different annotations, but the instance name is log, There are six kinds of optional implementation class * @ CommonsLog Creates the log = org.apache.com mons. Logging. LogFactory. GetLog (LogExample. Class); * @Log Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName()); * @Log4j Creates log = org.apache.log4j.Logger.getLogger(LogExample.class); * @Log4j2 Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class); * @Slf4j Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class); * @XSlf4j Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);Copy the code

Lombok code demonstrations

Code Example:

  • Val declares the variable as final

    public static void main(String[] args) { val sets = new HashSet(); val lists = new ArrayList(); val maps = new HashMap<String, String>(); Final Set sets2 = new HashSet<>(); final List lists2 = new ArrayList<>(); final Map<String, String> maps2 = new HashMap<>(); }

  • @nonNULL provides non-null checking for method and constructor arguments

    public void notNullExample(@NonNull String string) { string.length(); } public void notNullExample(String String) {if (String! = null) { string.length(); } else { throw new NullPointerException(“null”); }}

  • Cleanup Automatically frees resources

    public static void main(String[] args) { try { @Cleanup InputStream inputStream = new FileInputStream(args[0]); } catch (FileNotFoundException e) { e.printStackTrace(); } InputStream InputStream = null; try { inputStream = new FileInputStream(args[0]); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (inputStream ! = null) { try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); }}}}

  • @getter / @setter automatically generates Get/Set methods for class property fields

    @Setter(AccessLevel.PUBLIC)@Getter(AccessLevel.PROTECTED)private int id; private String shap;

  • @toString generates a ToString method for the class

    @ToString(exclude = “id”, callSuper = true, includeFieldNames = true)public class LombokDemo { private int id; private String name; private int age; Public static void main(String[] args) {LombokDemo(super=LombokDemo@48524010, name=null, age=0) System.out.println(new LombokDemo()); }}

  • @equalSandhashCode generates equals and hasCode methods for the class

    @EqualsAndHashCode(exclude = {“id”, “shape”}, callSuper = false)public class LombokDemo { private int id; private String shap; }

  • @noargsconstructor, @requiredargsconstructor and @allargsconstructor, respectively, automatically generate no-argument constructs for the class, specifying a parameter constructor and containing all parameter constructors

    @NoArgsConstructor@RequiredArgsConstructor(staticName = “of”)@AllArgsConstructorpublic class LombokDemo { @NonNull private int id; @NonNull private String shap; private int age; public static void main(String[] args) { new LombokDemo(1, “circle”); // Use the static factory method lombokdemo. of(2, “circle”); // Construct new LombokDemo() with no arguments; New LombokDemo(1, “circle”, 2); }}

  • Using @data on a class is equivalent to using the @toString, @equalSandHashCode, @getter, @setter, and @requiredargsConstructor annotations together

    import lombok.Data; @Datapublic class Menu { private String shopId; private String skuMenuId; private String skuName; private String normalizeSkuName; private String dishMenuId; private String dishName; private String dishNum; Private float thresHold = 0; // newThresHold private float newThresHold = 0; // private float totalScore = 0; }

  • @value adds a final declaration for a property

    @Valuepublic class LombokDemo { @NonNull private int id; @NonNull private String shap; private int age; Private final int id; public int getId() { return this.id; }… }

  • @Builder provides a way to build value objects

    @Builderpublic class BuilderExample { private String name; private int age; @Singular private Set occupations; public static void main(String[] args) { BuilderExample test = BuilderExample.builder().age(11).name(“test”).build(); }}

  • @sneakythrows automatically checked exceptions

    import lombok.SneakyThrows; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.UnsupportedEncodingException; public class Test { @SneakyThrows() public void read() { InputStream inputStream = new FileInputStream(“”); } @SneakyThrows public void write() { throw new UnsupportedEncodingException(); Public void read() throws FileNotFoundException {InputStream InputStream = new FileInputStream(“”); } public void write() throws UnsupportedEncodingException { throw new UnsupportedEncodingException(); }}

  • @synchronized synchronizes method declarations and automatically locks them

    public class SynchronizedDemo { @Synchronized public static void hello() { System.out.println(“world”); } private static final Object LOCK = new Object[0]; public static void hello() { synchronized (LOCK) { System.out.println(“world”); }}}

  • Getter(lazy=true) can replace the classic Double Check Lock boilerplate code

    public class GetterLazyExample { @Getter(lazy = true) private final double[] cached = expensive(); private double[] expensive() { double[] result = new double[1000000]; for (int i = 0; i < result.length; i++) { result[i] = Math.asin(i); } return result; }} / / equivalent as follows: the import of Java. Util. Concurrent. Atomic. AtomicReference; public class GetterLazyExample { private final AtomicReference<java.lang.Object> cached = new AtomicReference<>(); public double[] getCached() { java.lang.Object value = this.cached.get(); if (value == null) { synchronized (this.cached) { value = this.cached.get(); if (value == null) { final double[] actualValue = expensive(); value = actualValue == null ? this.cached : actualValue; this.cached.set(value); } } } return (double[]) (value == this.cached ? null : value); } private double[] expensive() { double[] result = new double[1000000]; for (int i = 0; i < result.length; i++) { result[i] = Math.asin(i); } return result; }}

  • @log generates different types of Log objects based on different annotations

    * @CommonsLog Creates log = org.apache.commons.logging.LogFactory.getLog(LogExample.class);    * @Log Creates log = java.util.logging.Logger.getLogger(LogExample.class.getName());    * @Log4j Creates log = org.apache.log4j.Logger.getLogger(LogExample.class);    * @Log4j2 Creates log = org.apache.logging.log4j.LogManager.getLogger(LogExample.class);    * @Slf4j Creates log = org.slf4j.LoggerFactory.getLogger(LogExample.class);    * @XSlf4j Creates log = org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);
    Copy the code

conclusion

That’s the end of this introduction to Lombok, and there will be more articles in the Lombok series to come. Thank you for your support!

“Like” to prove you still love me