@Getter和@Setter
2017-07-17 本文已影响11196人
github加星点进来
@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;
}
}