目前碰到lombok.jar的一個插件,使用還是不錯的,可以消除類中setter、gettter的方法,可以讓代碼更簡潔。
lombok的官網:https://projectlombok.org/
安裝
1、官網中下載lombok.jar文件
2、雙擊下載的lombok.jar 就會幫你自動安裝。其實這個步驟就是把lombok.jar放置到eclipse的路徑下,並在eclipse.ini中最後一行添加-javaagent:lombok.jar
註解
@Getter:註解在屬性上,提供 getter 方法;
@Setter:註解在屬性上,提供 setter 方法;
@AllArgsConstructor:註解在類上,提供構造方法,參數爲所有屬性;
@NoArgsConstructor:註解在類上,提供無參構造方法;
@Data:註解在類上,提供所有屬性的 getter 方法、setter 方法以及 equals、hashCode、toString 等方法;
@Log:註解在類上,提供一個名爲 log 的屬性,類型爲 java.util.logging.Logger,也可使用 @Log4j、@Log4j2、@Slf4j 等其他註解;
@ToString:註解在類上,提供 toString 方法;
@EqualsAndHashCode:註解在類上,提供 equals、hashCode 方法;
@Synchronized:註解在方法上,提供 synchronized,可以指定鎖的名稱;
@NonNull:註解在方法參數上,提供對參數的校驗,防止空指針異常;
@Cleanup:註解在局部變量上,提供對資源的關閉,即調用 close 方法;
簡化後的代碼
@NoArgsConstructor
@AllArgsConstructor
public @Data class Person {
private String name;
}
編譯上述代碼後
import java.beans.ConstructorProperties;
public class Person {
private String name;
public Person() {
}
@ConstructorProperties({ "name" })
public Person(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Person))
return false;
Person other = (Person) o;
if (!other.canEqual(this))
return false;
Object this$name = getName();
Object other$name = other.getName();
return this$name == null ? other$name == null : this$name.equals(other$name);
}
protected boolean canEqual(Object other) {
return other instanceof Person;
}
public int hashCode() {
int PRIME = 59;
int result = 1;
Object $name = getName();
return result * 59 + ($name == null ? 43 : $name.hashCode());
}
public String toString() {
return "Person(name=" + getName() + ")";
}
}
這個插件簡化了大量樣式代碼,使得代碼非常乾淨,不過會導致可讀性比較差,個人覺得用起來還是挺不錯的。