@Getter和@Setter 出現的目的是
public int getFoo() {return foo;} 不需要在寫get 和 set 方法。
您可以使用@Getter或@Setter來註釋任何字段,以使lombok自動生成默認的getter / setter。
lombok生成的getter / setter方法默認作用域將是public
除非你明確指定一個AccessLevel
如下面的例子所示。作用域級別PUBLIC,PROTECTED,PACKAGE,和PRIVATE。
你也可以在class 上面放置@Getter和/或@Setter註釋。在這種情況下,就好像您使用註釋註釋該類中的所有非靜態字段。
使用了Lombok 代碼
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
public class GetterSetterExample {
/**
* Age of the person. Water is wet.
*
* @param age New value for this person's age. Sky is blue.
* @return The current value of this person's age. Circles are round.
*/
@Getter @Setter private int age = 10;
/**
* Name of the person.
* -- SETTER --
* Changes the name of this person.
*
* @param name The new value.
*/
@Setter(AccessLevel.PROTECTED) private String name;
@Override public String toString() {
return String.format("%s (age: %d)", name, age);
}
}
默認的代碼是(未使用lombok)
public class GetterSetterExample {
/**
* Age of the person. Water is wet.
*/
private int age = 10;
/**
* Name of the person.
*/
private String name;
@Override public String toString() {
return String.format("%s (age: %d)", name, age);
}
/**
* Age of the person. Water is wet.
*
* @return The current value of this person's age. Circles are round.
*/
public int getAge() {
return age;
}
/**
* Age of the person. Water is wet.
*
* @param age New value for this person's age. Sky is blue.
*/
public void setAge(int age) {
this.age = age;
}
/**
* Changes the name of this person.
*
* @param name The new value.
*/
protected void setName(String name) {
this.name = name;
}
}
要在生成的方法上註釋,可以使用onMethod=@({@AnnotationsHere}); 將註釋放在生成的setter方法的唯一參數上,可以使用onParam=@({@AnnotationsHere})。小心!這是一個實驗功能。
getter / setter參數
lombok.AccessLevel value() default lombok.AccessLevel.PUBLIC;
lombok.Getter.AnyAnnotation[] onMethod() default {};
boolean lazy() default false;
getter / setter使用方法
package me.wonwoo;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
public class GetSetObject {
// @Setter(onParam = @__({@NotNull}), onMethod = @__({@NotNull}))
@Setter(onMethod = @__({@NotNull}))
// @Getter(value = AccessLevel.PUBLIC, onMethod = @__({@NonNull, @Id}))
private Long id;
// @Getter
@Getter(value = AccessLevel.PUBLIC, lazy = true)
private final String name = expensive();
private String expensive() {
return "wonwoo";
}
}
class GetSetObjectOnParam {
private Long id;
public void setId(@NotNull Long id) {
this.id = id;
}
}
class GetSetObjectOnMethod {
private Long id;
@Id
@Column(name = "seq")
Long getId() {
return id;
}
}
作者:二月長河
鏈接:https://www.jianshu.com/p/93353398e964
來源:簡書
著作權歸作者所有。商業轉載請聯繫作者獲得授權,非商業轉載請註明出處。