Elegant Java Tool Library Lombok

Source: Internet
Author: User
Tags log log jboss log4j

Elegant Java Tool Library Lombok

Recently in the company's project to see the application of the Lombok, through the @data annotations annotated Pojo, omit a lot of getter/setter code, the original long pojo in thin body directly become clean, refreshing, programmers no longer need to pay attention to the length of the method, You just need to focus on the field.

Lombok Introduction

Lombok is a very useful library of Java tools that effectively simplifies the verbosity of Java code. It uses annotations such as @data to dynamically generate field Getter/setter methods for Java beans at compile time, using annotations @noargsconstructor and @allargsconstructor as Java The Bean adds a parameterless constructor and a parametric constructor, and can even use Val and var to declare a dynamic variable in Java code without specifying a specific variable type, except that the Val-declared variable is final. Lombok also provides delombok for generation Javadoc,delombok to convert annotation @data to Getter/setter method at run time, then remove @data annotations, and if Lombok is no longer needed, You just have to run Delombok simply. Lombok's build supports Maven and Gradle, while mainstream Ides such as Eclipse, MyEclipse, and Idea are also Lombok compatible, so you can use Lombok with confidence, without worrying about IDE compilation checking.

Lombok Chestnut Eclipse Installation Lombok Support

Official website Lombok https://projectlombok.org/download Download the jar package or download the jar package from the build tool Maven,gradle

Double-click the jar package and the installer inside the jar package will run automatically looking for eclipse

Click "Install/update"

Introducing Lombok Dependencies
    <dependency>        <groupId>org.projectlombok</groupId>        <artifactId>lombok</artifactId>        <version>1.18.2</version>        <scope>provided</scope>    </dependency>
Lombok annotations Using

Lombok's annotations are divided into stable versions and trial versions, which mainly introduce stable versions, because the pilot version of support is currently not very good for the IDE

@Getter/@Setter Annotations

The purpose of the @Getter/@Setter annotation is to add a Getter/setter method to the field that can be labeled on a class or labeled on a field. A callout representing all non-static (no-static) fields on a class generates a corresponding Getter/setter method, which indicates that the field is generated for this field only and overrides annotations on the class. You can set the access level, which is public by default. @Setter can not label final fields

@[email protected]public class SetterExample {        @Getter(value=AccessLevel.PRIVATE)@Setter    private String name;        //[email protected]__({@AnnotationsHere})    @Setter([email protected]__({@Deprecated}))    private String age;        //[email protected]__({@AnnotationsHere})    @Setter([email protected]__({}))    private String sex;        public static void main(String[] args) {        SetterExample se = new SetterExample();        se.setName("zhangsan");        se.setAge("16");        System.out.println(se.getAge());        System.out.println(se.getName());    }}

Lombok provides Onx test properties, namely: Onmethod, Onparam, Onconstructor, for adding annotations to the generated method, constructor, parameter

Post-compilation results

@NonNull annotations

@NonNull Annotation Labeling methods and constructor parameters, if the argument is null, a null pointer exception is thrown, and no null detection is required in the code

public class NonNullExample {        @Getter    private String name;        public NonNullExample(@NonNull String name){        this.name = name;    }        public static void main(String[] args){        String name = null;        NonNullExample nne = new NonNullExample(name);        System.out.println(nne.getName());    }}
@ToString annotations

@ToString annotation Generation ToString () method

@ToStringpublic class ToStringExample {    @ToString.Exclude    private String name;        @ToString.Include    private String age;        private String sex;        public static void main(String[] args) {        ToStringExample tse = new ToStringExample();        System.out.println(tse.toString());    }}

Property Includefieldnames, Default = True, contains the property value

The Callsuper property, which defaults to false, invokes the parent class implementation

Property onlyexplicitlyincluded, Default = False, contains only explicitly contained properties

@ToString. Exclude dimension attribute values are not included in the ToString () method

@ToString. Include label property values are included in the ToString () method

@EqualsAndHashCode

@EqualsAndHashCode annotations generate the Equals () and Hashcode () methods, and the annotation properties are similar to @tostring

@EqualsAndHashCodepublic class EqualsAndHashcodeExample {    private String name;    private String age;    private String sex;        public static void main(String[] args) {        EqualsAndHashcodeExample ehe1 = new EqualsAndHashcodeExample();        EqualsAndHashcodeExample ehe2 = new EqualsAndHashcodeExample();        System.out.println(ehe1.equals(ehe2));        System.out.println(ehe1.hashCode());        System.out.println(ehe2.hashCode());    }}
@[email protected] @AllArgsConstructor

@NoArgsConstructor: Creating a parameterless construction method

@NoArgsConstructor(force=true, staticName="newInstance")public class NoArgsConstructorExample {    //包含的final字段如果没有初始化,需要加上force=true强制初始化,否则编译错误    private final String name;        //不会进行null检查    @NonNull    @Getter    private String age;        private String sex;        public static void main(String[] args) {        NoArgsConstructorExample nace1 = new NoArgsConstructorExample();        System.out.println(nace1.getAge());        NoArgsConstructorExample nace2 = NoArgsConstructorExample.newInstance();        System.out.println(nace2.getAge());    }}

@RequiredArgsConstructor: A construction method that contains constants, and variables that identify Notnull, is generated.

@RequiredArgsConstructor(staticName="newInstance")public class RequiredArgsConstructorExample {    private final String name;        @NonNull    @Getter    private String age;        private String sex;        public static void main(String[] args) {        RequiredArgsConstructorExample race1 = new RequiredArgsConstructorExample("lisi", "18");        System.out.println(race1.getAge());        RequiredArgsConstructorExample race2 = RequiredArgsConstructorExample.newInstance("zhangsan", "16");        System.out.println(race2.getAge());    }}

@AllArgsConstructor: Generates a check that contains all the variables, and if the variable uses notnull annotation, it will be empty

@AllArgsConstructor(staticName="newInstance")public class AllArgsConstructorExample {    private final String name;        @NonNull    @Getter    private String age;        private String sex;    public static void main(String[] args) {        AllArgsConstructorExample aace1 = new AllArgsConstructorExample("zhangsan", "18", "female");        System.out.println(aace1.getAge());        AllArgsConstructorExample aace2 = AllArgsConstructorExample.newInstance("lisi", "16", "male");        System.out.println(aace2.getAge());    }}

Note: The constructors generated by the three annotations can specify access rights and can also provide a static method for invocation. The difference between the three annotations is that the final and @nonnull fields are treated differently

In addition to the Staticname attribute, the Lombok source notes are as follows:

If set, the generated constructor will be private, and an additional static ‘constructor‘ is generated with the same argument list that wraps the real constructor.

It is obvious that three annotations can be created directly using the constructor, or you can create an object using a static method, and you do not know what this comment means???

@Data annotations

Equivalent to @tostring, @EqualsAndHashcode, @Getter, @Setter with @requiredargsconstructor

@Value

@Value annotations are @data of immutable types and are a variant of @data. The classes and fields it labels are declared final

@Builder annotations

@Builder annotations generate the builder API for the class to invoke. Builder is a way to build a class that addresses a large and complex number of fields.

If a class has dozens of fields, how do you design this class?

Method One: Add dozens of fields to the constructor. Simple and rude, and initializing the field in the constructor also guarantees that the object can be created correctly. The downside is that dozens of parameters can only cause you to mistake the location of the parameter when creating the object, causing unnecessary trouble.

Method Two: Dependency injection. One of spring's core functions is dependency injection, which allows us to create an object through a parameterless construct and then set the required properties through the setter method. This method can initialize the related attributes according to the requirements, and the logic is clear, but also cause the code cumbersome, need to call multiple setter method.

Method Three: Builder mode. The idea of the builder model is to create a large class of constructs into several parts, simplifying the complexity of the creation.

@Builderpublic class BuilderExample {    private String name;    private String age;    private String sex;    public static void main(String[] args) {        BuilderExample be = BuilderExample.builder().name("zhangsan").age("16").sex("male").build();                System.out.println(BuilderExample.builder().name("zhangsan").age("16").sex("male"));    }}

@Log

@Log annotations Add a Log object to the class logs, type Java.util.logging.Logger

There are many variants of this class, as detailed below:

  @CommonsLogprivate static final Org.apache.commons.logging.Log Log = Org.apache.commons.logging.LogFactory.getLog (logexample.class); @Floggerprivate static final Com.google.common.flogger.FluentLogger log = Com.google.common.flogger.FluentLogger.forEnclosingClass (); Jbosslogprivate static final Org.jboss.logging.Logger log = Org.jboss.logging.Logger.getLogger (Logexample.class); Logprivate static final Java.util.logging.Logger log = Java.util.logging.Logger.getLogger (LogExample.class.getName () ); @Log4jprivate static final Org.apache.log4j.Logger log = Org.apache.log4j.Logger.getLogger (logexample.class); @ Log4j2private static final Org.apache.logging.log4j.Logger log = Org.apache.logging.log4j.LogManager.getLogger ( Logexample.class); @Slf4jprivate static final Org.slf4j.Logger log = Org.slf4j.LoggerFactory.getLogger ( Logexample.class); @XSlf4jprivate static final Org.slf4j.ext.XLogger log = Org.slf4j.ext.XLoggerFactory.getXLogger ( Logexample.class);  
@CleanUp annotations

@CleanUp Annotations for closing resources, calling the close () method of a resource

public class CleanUpExample {        @SneakyThrows({FileNotFoundException.class, Exception.class})    public static void main(String[] args) {        File file = new File("C:/Users/wang2/Desktop/11.jpg");        @Cleanup        FileInputStream is = new FileInputStream(file);        @Cleanup        FileOutputStream os = new FileOutputStream(new File("C:/Users/wang2/Desktop/111.jpg"));                byte[] buffer = new byte[1024];        int length = 0;        while((length = is.read(buffer)) != -1){            os.write(buffer, 0, length);        }    }}

Note: The thrown exception was captured by @sneakythrows

@SneakyThrows annotations

Sneaky means sneaking around, @SneakyThrows annotations are replacing try...catch blocks of code and automatically generating corresponding Try...catch code blocks

Elegant Java Tool Library Lombok

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.