lombok中的@builder注解怎么用-mile米乐体育
lombok中的@builder注解怎么用
这篇文章主要介绍lombok中的@builder注解怎么用,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
lombok中的@builder注解的使用
作用
@builder注解的作用主要是用来生成对象,并且可以为对象链式赋值。
引入依赖
因为@builder注解是lombok中的东西,所以第一步我们需要引入lombok的依赖,如下图:
第二步给实体类加上@builder注解
第二步我们需要给我们的实体类加上一个@builder注解,如下图:
第三步使用测试使用@builder注解生成对象
实体类加上@builder注解之后的编译结果
实体类加上@builder注解之后,编译之后会多出一个builder()方法,和一个cardbuilder静态内部类,如下图:
代码如下:
publicclasscard{privateintid;privatestringname;privatebooleansex;publicstaticcard.cardbuilderbuilder(){returnnewcard.cardbuilder();}publiccard(intid,stringname,booleansex){this.id=id;this.name=name;this.sex=sex;}publiccard(){}publicintgetid(){returnthis.id;}publicstringgetname(){returnthis.name;}publicbooleanissex(){returnthis.sex;}publicvoidsetid(intid){this.id=id;}publicvoidsetname(stringname){this.name=name;}publicvoidsetsex(booleansex){this.sex=sex;}publicbooleanequals(objecto){if(o==this){returntrue;}elseif(!(oinstanceofcard)){returnfalse;}else{cardother=(card)o;if(!other.canequal(this)){returnfalse;}elseif(this.getid()!=other.getid()){returnfalse;}else{objectthis$name=this.getname();objectother$name=other.getname();if(this$name==null){if(other$name==null){returnthis.issex()==other.issex();}}elseif(this$name.equals(other$name)){returnthis.issex()==other.issex();}returnfalse;}}}protectedbooleancanequal(objectother){returnotherinstanceofcard;}publicinthashcode(){intprime=true;intresult=1;intresult=result*59 this.getid();object$name=this.getname();result=result*59 ($name==null?43:$name.hashcode());result=result*59 (this.issex()?79:97);returnresult;}publicstringtostring(){return"card(id=" this.getid() ",name=" this.getname() ",sex=" this.issex() ")";}publicstaticclasscardbuilder{privateintid;privatestringname;privatebooleansex;cardbuilder(){}publiccard.cardbuilderid(intid){this.id=id;returnthis;}publiccard.cardbuildername(stringname){this.name=name;returnthis;}publiccard.cardbuildersex(booleansex){this.sex=sex;returnthis;}publiccardbuild(){returnnewcard(this.id,this.name,this.sex);}publicstringtostring(){return"card.cardbuilder(id=" this.id ",name=" this.name ",sex=" this.sex ")";}}}
以上是“lombok中的@builder注解怎么用”这篇文章的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注恰卡编程网行业资讯频道!