Using Lombok to simplify unnecessary Java code in your project

Source: Internet
Author: User

When writing to use Java, there will inevitably be some template code to write, otherwise get/set,tostring, hashcode, close resources, define constructors and so on. The code will look very redundant and very long. Lombok project can be we get rid of these things, through a series of annotations, Lombok can help us to automatically generate these functions.

Lombok website Address: https://projectlombok.org/

Reference Document: Https://projectlombok.org/features/index.html

1. Installation

Download Lombok.jar on the website, double-click and follow the prompts to install successfully in eclipse.

If you use MAVEN, you need to introduce dependencies:

    <Dependency>         <groupId>Org.projectlombok</groupId>         <Artifactid>Lombok</Artifactid>         <version>1.16.4</version>         <Scope>Provided</Scope>     </Dependency>

If you need to compile the Java class with Javac or other command tools, you need to put Lombok.jar into classpath.

2. How to use (document: https://projectlombok.org/features/index.html)

1> @Getter/@Setter, annotations on a Pojo class, the Get/set function is automatically generated at compile time for us.

2> @ToString Annotations on the class, compile, help us to generate the ToString function including all field;

3> @EqualsAndHashCode, compile, help us generate Equlas and hashcode functions;

4> @Cleanup, annotations in the definition of some resource objects, can help us to automatically call their close () function;这个很有帮助;

5> @NoArgsContructor, @RequireArgsContructor, @AllArgsContructor, respectively, to help us generate parameterless constructors, each of the constructors of a non-null field, constructor for all field parameters;

6> @Data, all together now:a shortcut for @ToString ,, in all fields, and on all @EqualsAndHashCode @Getter non-final fields, and @Setter ! (Equivalent to: @ToString ,,, @EqualsAndHashCode @Getter @Setter , @RequiredArgsConstructor )

For more annotations, see https://projectlombok.org/features/index.html

3. Example

 Public class Test {    privateint  ID;     Private String name;     Private String password;      Public Static void Main (string[] args) {        new Test (1, "Test", "password");        SYSTEM.OUT.PRINTLN (test);        System.out.println (Test.getname ());}    }

Results:

Test (id=1, name=test, password=password) test

The constructor for the full field parameter of Test is automatically generated, and the ToString (), Get/set function and so on are generated automatically. Look at another example:

     Public Static voidMain (string[] args)throwsioexception{@Cleanup InputStream in=NewFileInputStream ("/home/a.txt"); @Cleanup OutputStream out=NewFileOutputStream ("/home/b.txt"); byte[] B =New byte[10000];  while(true) {            intR =In.read (b); if(r = =-1)                 Break; Out.write (b,0, R); }    }

@Cleanup automatically help us to close the resource by calling the close () method.

@Cleanupensure a given resource is automatically cleaned up before the code execution path exits your Scope. annotating any local variable declaration with the annotation as so @Cleanup :
@Cleanup InputStream in = new FileInputStream("some/file");
as a result, at the end of the scope of your ' re in, is in.close() called. this are guaranteed to run by the atry/finally construct.

If the type of object you ' d like to cleanup does not has a close() method, but some other no-argument method, you Canspecify the name of this method:
@Cleanup("dispose") org.eclipse.swt.widgets.CoolBar bar = new CoolBar(parent, 0);
By default, the cleanup method was presumed close() to be. A Cleanup method that takes 1 or more arguments cannot is called via @Cleanup .

@Cleanup is implemented through try/finally, if the resource's Close method is not the default close (), you can also specify the name of the Close method @cleanup ("CloseMethod"), but the shutdown method cannot have parameters. Otherwise you won't be able to use the @Cleanup.

For more reference https://projectlombok.org/features/index.html

By using Lombok, you can reduce the amount of Java code and relieve the psychological burden.

Use Lombok to simplify unnecessary Java code in your project

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.