介绍
lombok已经在越来越多的项目中进行使用了。通过简单的注解就可以去除繁琐的get,set方法,我觉得最方便的还是他的@bulider注解。通过这个注解就对应着设计模式中的建造者模式,可以很方便的获得一个类,也可以链式的进行对象的赋值操作。
Lombok中的@bulider实现
在idea中,进行maven的clean,install。就可以看到对应的红色的target文件,target文件中放着对应的java类编译后形成的类。这样我们就可以看到lombok替我们做了什么了。
可以看到他在对应的java对象buliderPerson中实现了一个内部buliderPersonBuilder类来进行对应的原先的类的构建。他的属性和buliderPserion一模一样,set的时候返回的也是这个buliderPersonBuilder类本身,这样也实现了链式编程。这样也符合建造者模式的特征。外部调用无需关注内部逻辑,只需要bulider便可以获得需要的结果类即可。
原来的类
import lombok.Builder;
import lombok.Data;
@Data
@Builder
public class BuilderPerson {
private String name;
private int age;
public static void main(String[] args) {
BuilderPerson builderPerson = BuilderPerson.builder().name("test").age(1).build();
System.out.println(builderPerson.getAge());
System.out.println(builderPerson.getName());
}
//结果为:
//1
//test
}
编译后的类
public class BuilderPerson {
private String name;
private int age;
BuilderPerson(final String name, final int age) {
this.name = name;
this.age = age;
}
public static BuilderPerson.BuilderPersonBuilder builder() {
return new BuilderPerson.BuilderPersonBuilder();
}
private BuilderPerson() {
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public void setName(final String name) {
this.name = name;
}
public void setAge(final int age) {
this.age = age;
}
public boolean equals(final Object o) {
if (o == this) {
return true;
} else if (!(o instanceof BuilderPerson)) {
return false;
} else {
BuilderPerson other = (BuilderPerson)o;
if (!other.canEqual(this)) {
return false;
} else {
Object this$name = this.getName();
Object other$name = other.getName();
if (this$name == null) {
if (other$name == null) {
return this.getAge() == other.getAge();
}
} else if (this$name.equals(other$name)) {
return this.getAge() == other.getAge();
}
return false;
}
}
}
protected boolean canEqual(final Object other) {
return other instanceof BuilderPerson;
}
public int hashCode() {
int PRIME = true;
int result = 1;
Object $name = this.getName();
int result = result * 59 + ($name == null ? 43 : $name.hashCode());
result = result * 59 + this.getAge();
return result;
}
public String toString() {
return "BuilderPerson(name=" + this.getName() + ", age=" + this.getAge() + ")";
}
public static class BuilderPersonBuilder {
private String name;
private int age;
BuilderPersonBuilder() {
}
public BuilderPerson.BuilderPersonBuilder name(final String name) {
this.name = name;
return this;
}
public BuilderPerson.BuilderPersonBuilder age(final int age) {
this.age = age;
return this;
}
public BuilderPerson build() {
return new BuilderPerson(this.name, this.age);
}
public String toString() {
return "BuilderPerson.BuilderPersonBuilder(name=" + this.name + ", age=" + this.age + ")";
}
}
}