使用 Lombok 簡化項目中無謂的Java代碼

來源:互聯網
上載者:User

標籤:

在寫使用Java時,難免會有一些模板代碼要寫,不然get/set,toString, hashCode, close 資源,定義建構函式等等。代碼會顯得很冗餘,很長。Lombok項目可以是我們擺脫這些東西,通過一系列的註解,Lombok可以幫我們自動產生這些函數。

Lombok 官網地址:https://projectlombok.org/

參考文檔:https://projectlombok.org/features/index.html

1. 安裝

到官網下載 lombok.jar,直接雙擊,按照提示進行操作,就可以在eclipse中安裝成功。

如果使用maven時,則需要引入依賴:

    <dependency>         <groupId>org.projectlombok</groupId>         <artifactId>lombok</artifactId>         <version>1.16.4</version>         <scope>provided</scope>     </dependency>

如果需要用javac或者其他命令工具編譯java類,則需要將 lombok.jar放入classpath.

2. 使用方法 (文檔:https://projectlombok.org/features/index.html)

1> @Getter/@Setter, 註解在一個pojo類上,會在編譯時間,幫我們自動產生get/set函數。

2> @ToString 註解在類上,編譯時間,幫我們產生包括所有field的toString函數;

3> @EqualsAndHashCode,  編譯時間,幫我們產生equlas 和hashCode函數;

4> @Cleanup, 註解在一些資來源物件的定義上,可以幫我們自動調用它們的close()函數;這個很有協助;

5> @NoArgsContructor,@RequireArgsContructor, @AllArgsContructor,分別幫我們產生無參數建構函式,每一個非Null的field的建構函式,所有field參數的建構函式;

6> @Data,All together now: A shortcut for @ToString, @EqualsAndHashCode, @Getter on all fields, and @Setter on all non-final fields, and @RequiredArgsConstructor! (等價於:@ToString, @EqualsAndHashCode, @Getter, @Setter, @RequiredArgsConstructor)

更多的註解,參見https://projectlombok.org/features/index.html

3. 例子

public class Test {    private int id;    private String name;    private String password;    public static void main(String[] args) {        Test test = new Test(1, "test", "password");        System.out.println(test);        System.out.println(test.getName());    }}

結果:

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

自動 產生了 Test 的全field參數的建構函式,自動產生了 toString(), get/set函數等等。再看一例:

    public static void main(String[] args) throws IOException{        @Cleanup        InputStream in = new FileInputStream("/home/a.txt");        @Cleanup        OutputStream out = new FileOutputStream("/home/b.txt");        byte[] b = new byte[10000];        while (true) {            int r = in.read(b);            if (r == -1)                break;            out.write(b, 0, r);        }    }

@Cleanup自動幫我們調用 close() 方法進行關閉資源。

You can use @Cleanup to ensure a given resource is automatically cleaned up before the code execution path exits your current scope. You do this by annotating any local variable declaration with the @Cleanup annotation like so:
@Cleanup InputStream in = new FileInputStream("some/file");
As a result, at the end of the scope you‘re in, in.close() is called. This call is guaranteed to run by way of atry/finally construct.

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

@Cleanup是通過 try/finally 實現的,如果資源的關閉方法不是預設的close(),那麼也可以指定關閉方法的名稱@Cleanup("closeMethod"), 但是關閉方法不能有參數,不然就無法使用 @Cleanup了。

更多的 參考 https://projectlombok.org/features/index.html

通過使用 Lombok,可以減少很多的 Java 代碼的,減輕了心理負擔。

 

使用 Lombok 簡化項目中無謂的Java代碼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.