前言Lombok是一个Java开发插件,可以让Java开发者通过它定义的一些注解来消除业务流程中的冗余代码,尤其是简单的Java模型对象(PO??JO)。而如果我们在开发环境中使用Lombok来开发插件,就可以节省大量的重复构建,hashCode、equals等方法,以及各种业务对象模型的accessor、ToString等方法的时间。对于这些方法,它可以在编译源码的时候自动帮我们生成这些方法,不会像反射那样降低程序的性能。本文将为您详细介绍Lombok的使用和原理。一、Lombok的概念《概念:》Lombok是一个Java实用程序,可以用来帮助开发人员消除冗余代码。对于一些简单的Java对象(PO??JO),它是通过注解来达到这个目的的。2、Lombok的安装《安装步骤:》在IDEA的Plugins中搜索Lombok安装Lombok《注意:》使用Lombok注解时,记得将Lombok.jar包导入到项目中。对于MavenProject,必须在pom.xml中添加依赖org.projectlomboklombok1.16.83.Lombok注解"常用注解:"Lombok注解*val:用在局部变量前面,相当于把变量声明为final*@NonNull:给方法参数加上这个注解,会自动检查方法中参数是否为null,如果为null则抛出NPE(NullPointerException)*@Cleanup:自动管理资源,在使用局部变量之前,在当前变量范围内退出前会自动清理资源,try-finally之类的代码会自动生成关闭流*@Getter/@Setter:用在属性上,不再需要自己写setter和getter方法,还可以指定访问范围*@ToString:用在类上,可以自动覆盖toString方法和c当然你可以添加其他参数,比如@ToString(exclude="id")排除id属性,或者@ToString(callSuper=true,includeFieldNames=true)调用父类的toString方法,包括所有属性*@EqualsAndHashCode:用在类上,自动生成equals方法和hashCode方法参数。如果指定了staticName="of"参数,也会生成一个返回类对象的静态工厂方法,比使用构造函数方便很多*@Data:注解在类上,相当于同时使用时间@ToString、@EqualsAndHashCode、@Getter、@Setter和@RequiredArgsConstrutor等注解对POJO类非常有用*@Value:用在类上,是@Data的不可变形式,相当于给属性加上final声明,只提供getter方法,不提供setter方法*@Builder:用在类、构造函数和方法上,为您提供复杂的builderAPI,允许您调用Person.builder().name("AdamSavage"),如下所示。city("SanFrancisco").job("Mythbusters").job("UnchainedReaction").build();更多解释参考Builder*@SneakyThrows:Automaticallythrowcheckedexceptionswithoutexplicitlyusethethrowsstatementonthemethod*@Synchronized:用在方法上,方法声明为synchronized,自动加锁,加锁对象是一个private属性$lock或$LOCK,而java中synchronized关键字lock对象就是this,锁在this中或者对自己的类对象有副作用,即无法阻止不受控制的代码对this或class对象加锁,这可能会导致竞争条件或其他线程错误*@Getter(lazy=true):可以替代经典的DoubleCheckLock样板代码*@Log:根据不同的注解生成不同类型的日志对象,但实例名称为log,并且有是六个可选的实现类*@CommonsLogCreateslog=org.apache.commons.logging.LogFactory.getLog(LogExample.class);*@LogCreateslog=java.util.logging.Logger.getLogger(LogExample.class.getName());*@Log4jCreateslog=org.apache.log4j.Logger.getLogger(LogExample.class);*@Log4j2Createslog=org.apache。logging.log4j.LogManager.getLogger(LogExample.class);*@Slf4jCreateslog=org.slf4j.LoggerFactory.getLogger(LogExample.class);*@XSlf4jCreateslog=org.slf4j.ext.XLoggerFactory.getXLogger(LogExample.class);4.Lombok代码演示《代码示例:》val声明变量为final类型publicstaticvoidmain(String[]args){valsets=newHashSet();vallists=newArrayList();valmaps=newHashMap();//=>等价于下面的finalSetsets2=newHashSet<>();finalListlists2=newArrayList<>();finalMapma??ps2=newHashMap<>();}@Nonnull为方法和构造函数提供参数非空检查publicvoidnotNullExample(@NonNullStringstring){string.length();}//=>等同于publicvoidnotNullExample(Stringstring){if(string!=null){string.length();}else{thrownewNullPointerException("null");}}@Cleanup自动释放资源printStackTrace();}//=>相当于InputStreaminputStream=null;试试{输入流=newFileInputStream(args[0]);}catch(FileNotFoundExceptione){e.printStackTrace();}最后{if(inputStream!=null){try{inputStream.close();}catch(IOExceptione){e.printStackTrace();}}}}@Getter/@Setter自动为类的属性字段生成Get/Set方法@Setter(AccessLevel.PUBLIC)@Getter(AccessLevel.PROTECTED)privateintid;privateStringshap;@ToString为类的属性字段生成toString方法class@ToString(exclude="id",callSuper=true,includeFieldNames=true)publicclassLombokDemo{privateintid;privateStringname;privateintage;publicstaticvoidmain(String[]args){//输出LombokDemo(super=LombokDemo@48524010,name=null,age=0)System.out.println(newLombokDemo());}}@EqualsAndHashCode为类@EqualsAndHashCode(exclude={"id","shape"},callSuper=false)生成equals和hasCode方法publicclassLombokDemo{privateintid;privateStringshap;}@NoArgsConstructor、@RequiredArgsConstructor和@AllArgsConstructor,自动为类生成无参构造,指定参数构造函数并包括所有参数构造函数@NoArgsConstructor@RequiredArgsConstructor(staticName="of")@AllArgsConstructorpublicclassLombokDemo{@NonNullprivateintid;@NonNullprivateStringshap;privateintage;publicstaticvoidmain(String[]args){newLombokDemo(1,"circle");//使用静态工厂方法LombokDemo.of(2,"circle");//构造newLombokDemo不带参数();//包含所有参数newLombokDemo(1,"circle",2);}}@Data用在类上,相当于使用@ToString、@EqualsAndHashCode、@Getter、@Setter和@RequiredArgsConstructor同时注释importlombok。Data;@DatapublicclassMenu{privateStringshopId;privateStringskuMenuId;privateStringskuName;privateStringnormalizeSkuName;privateStringdishMenuId;privateStringdishName;privateStringdishNum;//ThedefaultthresholdprivatefloatthresHold=0;//ThenewthresholdprivatefloatnewThresHold=0attributefinDeclare@ValuepublicclassLombokDemo{@NonNullprivateintid;@NonNullprivateStringshap;privateintage;//相当于privatefinalintid;publicintgetId(){returnthis.id;}...}@Builder提供了一种构建值对象的方法@BuilderpublicclassBuilderExample{privateStringname;privateintage;@SingularprivateSetoccupations;公共静态无效主要(String[]args){BuilderExampletest=BuilderExample.builder().age(11).name("test").build();}}@SneakyThrows自动抛出检查异常importlombok.SneakyThrows;importjava.io.FileInputStream;importjava。io.FileNotFoundException;导入java.io。输入流;导入java。publicvoidread()throwsFileNotFoundException{InputStreaminputStream=newFileInputStream("");}publicvoidwrite()throwsUnsupportedEncodingException{thrownewUnsupportedEncodingException();}}@Synchronized方法声明同步自动加锁publicclassSynchronizedDemo{@Synchronizedpublicstaticvoidhello()n(System.out.");}//相当于privatestaticfinalObject$LOCK=newObject[0];publicstaticvoidhello(){synchronized($LOCK){System.out.println("world");}}}@Getter(lazy=true)即可替换了经典的双重检查锁定模板代码publicclassGetterLazyExample{@Getter(lazy=true)privatefinaldouble[]cached=expensive();privatedouble[]expensive(){double[]result=newdouble[1000000];for(inti=0;icached=newAtomicReference<>();publicdouble[]getCached(){java.lang.Objectvalue=this.cached.get();if(value==null){synchronized(this.cached){value=this.cached.get();如果(值==null){finaldouble[]actualValue=expensive();value=actualValue==null?this.cached:actualValue;this.cached.set(value);}}}return(double[])(value==this.cached?null:value);}privatedouble[]expensive(){double[]result=newdouble[1000000];for(inti=0;i