減小代碼量工具-lombokjava
lombok的做用:消除模版代碼web
案例使用介紹:ide
1.添加pom.xml依賴:函數
<dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.8</version> <scope>provided</scope> </dependency>
2. 寫一個基礎類:工具
@Data @Builder public class Address { private int id; private String province; private String city; private String country; }
這裏須要說明一下,在傳統的Java開發中咱們須要重寫getter(),setter(),equals(),toString()等方法在這裏只須要定義註解便可:測試
因此在上面的例子中我只須要定義兩個註解便可省略大量的getter(),setter()等方法ui
以前咱們的代碼是這個樣子的this
package com.fastweb.web.model; import lombok.Builder; import lombok.Data; import lombok.extern.log4j.Log4j; public class Address { private int id; private String province; private String city; private String country; public Address(int id, String province, String city, String country) { this.id = id; this.province = province; this.city = city; this.country = country; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } @Override public String toString() { return "Address{" + "id=" + id + ", province='" + province + '\'' + ", city='" + city + '\'' + ", country='" + country + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Address address = (Address) o; if (id != address.id) return false; if (province != null ? !province.equals(address.province) : address.province != null) return false; if (city != null ? !city.equals(address.city) : address.city != null) return false; return country != null ? country.equals(address.country) : address.country == null; } @Override public int hashCode() { int result = id; result = 31 * result + (province != null ? province.hashCode() : 0); result = 31 * result + (city != null ? city.hashCode() : 0); result = 31 * result + (country != null ? country.hashCode() : 0); return result; } }
是否是很繁瑣code
lombok測試例子:xml
package com.fastweb.web.model; import lombok.extern.java.Log; import static org.junit.Assert.*; @Log public class AddressTest { public static void main(String[] args) { Address address = Address.builder().id(1001).city("wuhan").province("hubei").country("china").build(); log.info(address.toString()); } }
這裏只需定義@Log註解便可完成log的使用 很是方便 不再須要去定義額外的變量
最後貼一下lombok的使用說明 https://projectlombok.org/features/