在寫使用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. 例子
@Data@AllArgsConstructor@NoArgsConstructorpublic 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
通過@Data, @AllArgsConstructor,@NoArgsConstructor 三個注解自動 生成了 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 代碼的,減輕了心理負擔。
新聞熱點
疑難解答