Java效率工具Lombok使用及原理

1、前言 效率的提高

java效率的提高,一種方式就是去除模板代碼。java

1.1 去除pojo中的模板代碼

pojo 的 getter/setter/tostring,異常處理,io流的關閉操做。等重複代碼的出現。編程

解決方案:Lombok的使用。maven

2、lombok的使用

2.1 maven包

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

Lombok的scope=provided,說明它只在編譯階段生效,不須要打入包中。事實正是如此,Lombok在編譯期將帶Lombok註解的Java文件正確編譯爲完整的Class文件。ide

2.2 ide 工具對lombok的支持

idea 對 lombok的支持函數

https://mmbiz.qpic.cn/mmbiz_png/8yRv8Dibia2spfAUHyKgfqaAyP6mQxsicn1HmIsbvcrrliaRxcXwGmkWYQNdqtGtqia2xwM7oPSVibDgvv4gmI0SAshQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1工具

點擊File-- Settings設置界面,開啓Annocation Processors:測試

https://mmbiz.qpic.cn/mmbiz_png/8yRv8Dibia2spfAUHyKgfqaAyP6mQxsicn1MCjibH9fzFcsrtqvNRuXx7XF1iauzMic0tr8R0GkE6VtXRHLY0pk60xicQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1 ui

3、Lombok實現原理

自從Java 6起,javac就支持「JSR 269 Pluggable Annotation Processing API」規範,只要程序實現了該API,就能在javac運行的時候獲得調用。this

Lombok就是一個實現了"JSR 269 API"的程序。在使用javac的過程當中,它產生做用的具體流程以下:idea

1.javac對源代碼進行分析,生成一棵抽象語法樹(AST)

2.javac編譯過程當中調用實現了JSR 269的Lombok程序

3.此時Lombok就對第一步驟獲得的AST進行處理,找到Lombok註解所在類對應的語法樹(AST),而後修改該語法樹(AST),增長Lombok註解定義的相應樹節點

4.javac使用修改後的抽象語法樹(AST)生成字節碼文件

4、Lombok的使用

POJO類經常使用註解:

@Getter/@Setter: 做用類上,生成全部成員變量的getter/setter方法;做用於成員變量上,生成該成員變量的getter/setter方法。能夠設定訪問權限及是否懶加載等。

package com.trace;
import lombok.AccessLevel;import lombok.Getter;import lombok.Setter;
/** * Created by Trace on 2018/5/19.<br/> * DESC: 測試類 */@SuppressWarnings("unused")public class TestClass {
    public static void main(String[] args) {
    }

    
	@Getter(value = AccessLevel.PUBLIC)    
	@Setter(value = AccessLevel.PUBLIC)    
	public static class Person {        
	private String name;        
	private int age;        
	private boolean friendly;    
	}    
	
	public static class Animal {        
	private String name;        
	private int age;        
	@Getter @Setter private boolean funny;    
	}
}

在Structure視圖中,能夠看到已經生成了getter/setter等方法:

https://mmbiz.qpic.cn/mmbiz_png/8yRv8Dibia2spfAUHyKgfqaAyP6mQxsicn1sjPoKLwwwd3icuAlRJPBohzJuCFcuKbsXBkLtjlT8sW0ptIFHpYF26A/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1

編譯後的代碼以下:[這也是傳統Java編程須要編寫的樣板代碼]

//// Source code recreated from a .class file by IntelliJ IDEA// (powered by Fernflower decompiler)//
package com.trace;
public class TestClass {    public TestClass() {    }
    public static void main(String[] args) {    }
    public static class Animal {        private String name;        private int age;        private boolean funny;
        public Animal() {        }
        public boolean isFunny() {            return this.funny;        }
        public void setFunny(boolean funny) {            this.funny = funny;        }    }
    public static class Person {        private String name;        private int age;        private boolean friendly;
        public Person() {        }
        public String getName() {            return this.name;        }
        public int getAge() {            return this.age;        }
        public boolean isFriendly() {            return this.friendly;        }
        public void setName(String name) {            this.name = name;        }
        public void setAge(int age) {            this.age = age;        }
        public void setFriendly(boolean friendly) {            this.friendly = friendly;        }    }}

@ToString:做用於類,覆蓋默認的toString()方法,能夠經過of屬性限定顯示某些字段,經過exclude屬性排除某些字段。

https://mmbiz.qpic.cn/mmbiz_png/8yRv8Dibia2spfAUHyKgfqaAyP6mQxsicn1ZgPNh2ia7FpI73IpEs7RExObvPFmB6L7SjGHpYlVuEzibciaQGBicKHaFg/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1

@EqualsAndHashCode:做用於類,覆蓋默認的equals和hashCode

@NonNull:主要做用於成員變量和參數中,標識不能爲空,不然拋出空指針異常。

https://mmbiz.qpic.cn/mmbiz_png/8yRv8Dibia2spfAUHyKgfqaAyP6mQxsicn1xw0W3LiazGvffcuiaBvtGSmEpIM49bvlItIUojunQJt9MF2kvE4S1THg/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1

@NoArgsConstructor, @RequiredArgsConstructor, @AllArgsConstructor:做用於類上,用於生成構造函數。有staticName、access等屬性。

staticName屬性一旦設定,將採用靜態方法的方式生成實例,access屬性能夠限定訪問權限。

@NoArgsConstructor:生成無參構造器;

@RequiredArgsConstructor:生成包含final和@NonNull註解的成員變量的構造器;

@AllArgsConstructor:生成全參構造器。

https://mmbiz.qpic.cn/mmbiz_png/8yRv8Dibia2spfAUHyKgfqaAyP6mQxsicn14brDJrIRbocqfXmb5zVcuAvuv4syHO07kWGSENEYXmiaVDGETubYTPA/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1

編譯後結果:

public static class Person {    @NonNull    private String name;    private int age;    private boolean friendly;
    public String toString() {        return "TestClass.Person(name=" + this.getName() + ", age=" + this.getAge() + ")";    }
    @NonNull    public String getName() {        return this.name;    }
    public int getAge() {        return this.age;    }
    public boolean isFriendly() {        return this.friendly;    }
    public void setName(@NonNull String name) {        if(name == null) {            throw new NullPointerException("name");        } else {            this.name = name;        }    }
    public void setAge(int age) {        this.age = age;    }
    public void setFriendly(boolean friendly) {        this.friendly = friendly;    }
    private Person() {    }
    private static TestClass.Person of() {        return new TestClass.Person();    }
    @ConstructorProperties({"name"})    Person(@NonNull String name) {        if(name == null) {            throw new NullPointerException("name");        } else {            this.name = name;        }    }
    @ConstructorProperties({"name", "age", "friendly"})    public Person(@NonNull String name, int age, boolean friendly) {        if(name == null) {            throw new NullPointerException("name");        } else {            this.name = name;            this.age = age;            this.friendly = friendly;        }    }}

@Data:做用於類上,是如下註解的集合:@ToString @EqualsAndHashCode @Getter @Setter @RequiredArgsConstructor

@Builder:做用於類上,將類轉變爲建造者模式

@Log:做用於類上,生成日誌變量。針對不一樣的日誌實現產品,有不一樣的註解:

https://mmbiz.qpic.cn/mmbiz_png/8yRv8Dibia2spfAUHyKgfqaAyP6mQxsicn1v2AGjhq4XZkKdnzvQ1sz28d2KkKUbzsg2MDYA8jFhfQdKTOex0BvVA/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1

其餘重要註解:

@Cleanup:自動關閉資源,針對實現了java.io.Closeable接口的對象有效,如:典型的IO流對象

https://mmbiz.qpic.cn/mmbiz_png/8yRv8Dibia2spfAUHyKgfqaAyP6mQxsicn10IrJibxOKkfwkq5pYX3Gk37uR5CTibjnick2BYZhkicFWmEq5WlhU9s94Q/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1

編譯後結果以下:

https://mmbiz.qpic.cn/mmbiz_png/8yRv8Dibia2spfAUHyKgfqaAyP6mQxsicn1aeHtnFXX80ruePicibEKC249JaRnJFoPzequcwicpNzTZaibKtPTeeiagKQ/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1

是否是簡潔了太多。

@SneakyThrows:能夠對受檢異常進行捕捉並拋出,能夠改寫上述的main方法以下: https://mmbiz.qpic.cn/mmbiz_png/8yRv8Dibia2spfAUHyKgfqaAyP6mQxsicn1j3a5Ydyw36QYbcub1RQibIwW0yQ7IVWdOrbve7gSfXMdVFOLY2ysScw/640?wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1

@Synchronized:做用於方法級別,能夠替換synchronize關鍵字或lock鎖,用處不大。

連接

https://mp.weixin.qq.com/s?__biz=MzAxNjM2MTk0Ng==&mid=2247487090&idx=1&sn=7dd3dd6a5b950ec3edad6c379147b8e6&chksm=9bf4bec7ac8337d108ae04f5adf5ae204fd4c00e027878b513d960400619788d6a2949d6727c&mpshare=1&scene=1&srcid=0417WG1sRKF8wH5UBqh2MLlP&key=31930ee433f6b26f33bd0c6b152b3eec65be24598f76f0843cd3fb8f4bc401358929d5fa9ecd4fb11c1f81e8f11f5ce5430dab505d3d8e14dd2136788c93cd838ea4e759b53ee835c2cad89552fa3f55&ascene=1&uin=NjcwMTMyODE0&devicetype=Windows+10&version=62060739&lang=zh_CN&pass_ticket=9h8LTaxsCg0flxrGSmpRKdwWEqhq73NlLb5hbZW9tHci%2FcoXTCYsrXkDkIZpCcjJ

相關文章
相關標籤/搜索