1. What is Lombok Data annotation? - javabydeveloper Java ...
文章推薦指數: 80 %
Lombok Data annotation ( @Data ) Generates getters for all fields, a useful toString method, and hashCode and equals implementations that ... JavaNews CoreJava JUnit5 ORM JPAwithHibernate Lombok ContactUs Search javabydeveloperJavaTutorials Signin Welcome!Logintoyouraccount yourusername yourpassword Forgotyourpassword?Gethelp PrivacyPolicy Passwordrecovery Recoveryourpassword youremail Apasswordwillbee-mailedtoyou. javabydeveloperJavaTutorials JavaNews CoreJava JUnit5 ORM JPAwithHibernate Lombok ContactUs Search Signin/Join Facebook Twitter Pinterest WhatsApp Linkedin Email Telegram reportthisad HomeLombokLombokwith@Data Lombokwith@Data BySatishVarma March8,2021 InthisarticlewewillseewhatisLombokData(@Data)annotation,howitworkswithyourIDEandbuildtoolsandhowdoweuseitinjavawithaseveralexamples. MakesureyoualreadyinstalledLomboksetupforyourIDE.ToSetupinEclipseorinSpringToolSuiterefertoourLombokMavenexample+setupwithEclipse. TableofContent [hide]1.WhatisLombokDataannotation?2.Lombok@Dataexample3.HowLombokDataannotationworks?4.staticConstructor5.Lombok@Dataignore/excludefields6.Lombok@Dataand@BuildertogetherConclusion 1.WhatisLombokDataannotation? LombokDataannotation(@Data)Generatesgettersforallfields,ausefultoStringmethod,andhashCodeandequalsimplementationsthatcheckallnon-transientfields.Willalsogeneratesettersforallnon-finalfields,aswellasaconstructor.A@DataannotationsEquivalenttocombinationof @Getter@Setter@RequiredArgsConstructor@ToString@EqualsAndHashCode. 2.Lombok@Dataexample FollowingsidebysidecodedemonstratessimpleusageofLombok’s@DataannotationandhowlookslikeLombokgeneratedcodeexactlywhenyouuse@Dataannotation. LombokedUser1.java @Getter@Setter @RequiredArgsConstructor @ToString @EqualsAndHashCode publicclassUser1{ privateLongid; privateStringusername; } LombokedUser2.java @Data publicclassUser2{ privateLongid; privateStringusername; } Nowlet’shavealookintoLombokgenerated(Delomboked)codeforbothclasses. DeLombokedUser1.java publicclassUser1{ privateLongid; privateStringusername; publicLonggetId(){ returnthis.id; } publicStringgetUsername(){ returnthis.username; } publicvoidsetId(finalLongid){ this.id=id; } publicvoidsetUsername(finalStringusername){ this.username=username; } publicUser1(){ } @Override publicStringtoString(){ return"User1(id="+this.getId()+",username="+this.getUsername()+")"; } @Override publicbooleanequals(finalObjecto){ if(o==this) returntrue; if(!(oinstanceofUser1)) returnfalse; finalUser1other=(User1)o; if(!other.canEqual((Object)this)) returnfalse; finalObjectthis$id=this.getId(); finalObjectother$id=other.getId(); if(this$id==null?other$id!=null:!this$id.equals(other$id)) returnfalse; finalObjectthis$username=this.getUsername(); finalObjectother$username=other.getUsername(); if(this$username==null?other$username!=null:!this$username.equals(other$username)) returnfalse; returntrue; } protectedbooleancanEqual(finalObjectother){ returnotherinstanceofUser1; } @Override publicinthashCode(){ finalintPRIME=59; intresult=1; finalObject$id=this.getId(); result=result*PRIME+($id==null?43:$id.hashCode()); finalObject$username=this.getUsername(); result=result*PRIME+($username==null?43:$username.hashCode()); returnresult; } } DeLombokedUser2.java publicclassUser2{ privateLongid; privateStringusername; publicUser2(){ } publicLonggetId(){ returnthis.id; } publicStringgetUsername(){ returnthis.username; } publicvoidsetId(finalLongid){ this.id=id; } publicvoidsetUsername(finalStringusername){ this.username=username; } @Override publicbooleanequals(finalObjecto){ if(o==this) returntrue; if(!(oinstanceofUser2)) returnfalse; finalUser2other=(User2)o; if(!other.canEqual((Object)this)) returnfalse; finalObjectthis$id=this.getId(); finalObjectother$id=other.getId(); if(this$id==null?other$id!=null:!this$id.equals(other$id)) returnfalse; finalObjectthis$username=this.getUsername(); finalObjectother$username=other.getUsername(); if(this$username==null?other$username!=null:!this$username.equals(other$username)) returnfalse; returntrue; } protectedbooleancanEqual(finalObjectother){ returnotherinstanceofUser2; } @Override publicinthashCode(){ finalintPRIME=59; intresult=1; finalObject$id=this.getId(); result=result*PRIME+($id==null?43:$id.hashCode()); finalObject$username=this.getUsername(); result=result*PRIME+($username==null?43:$username.hashCode()); returnresult; } @Override publicStringtoString(){ return"User2(id="+this.getId()+",username="+this.getUsername()+")"; } } @Data generates all theboilerplatethatisnormallyassociatedwithsimplePOJOs(PlainOldJavaObjects)andbeans: gettermethodsforallfields,settermethodsforallnon-finalfields, appropriate toString(),appropriateequals() andhashCode() implementationsthatinvolvethefieldsoftheclass,anda constructor thatinitializesallfinalfields,aswellasall non-finalfields withnoinitializerthathavebeenmarkedwith @NonNull,inordertoensurethefieldisnevernull. Intheabovecode,twoapproachesareequal.@Dataannotationminimizestheusageofmoreannotationswhenyouneedtogeneratealltheabove7requirements,theyaremostcommonforthePojoclasses. 3.HowLombokDataannotationworks? Lombokannotation@DatasimplytellstotheIDE(eitherEclipseorSpringtoolSuiteorIntelliJetc)oryourbuildtoollikeMavenorAnt,togeneratealltheboilerplatecodeforyousilentlyduringcompiletime.Sothatuserneednottocreatethiscodeeverytimewhencreatedfields,developercanaccessallthesemethodsasusualwithinIDEwhilewritingcodefromthegenerated.classfile.Userscangetridofwritingallthatboilerplatecodejustbyadding@DataannotationtothePOJOclass. 4.staticConstructor IfyouspecifyastaticConstructorname,thenthegeneratedconstructorwillbeprivate,astaticfactorymethodiscreatedtothatotherclassescanusetocreateinstances. LombokedUser3.java @Data(staticConstructor="create") publicclassUser3{ privateLongid; privateStringusername; } DeLombokedUser3.java publicclassUser3{ privateLongid; privateStringusername; privateUser3(){ } publicstaticUser3create(){ returnnewUser3(); } //RestofcodesameasdelombokedUser3.java } 5.Lombok@Dataignore/excludefields @Dataannotationalonenotprovidesupportforignoringfieldsfromgeneratinggetters/settersortoStringorequalsandhashCodemethods.Followingexampledemonstrateshowtoexcludefieldswhenyouareusing@Dataannotation. @Data publicclassUser4{ @Setter(value=AccessLevel.NONE) privateLongid; @Getter(value=AccessLevel.NONE) privateStringusername; @ToString.Exclude privatebooleanactive; @EqualsAndHashCode.Exclude @ToString.Exclude privateintrole; } 6.Lombok@Dataand@Buildertogether Ifyouuse@Dataannotationalone,publicrequired-argsconstructorisgenerated.Ifyouareusing@Dataand@Builderannotationstogether,all-argsconstructor(Packageaccesslevel)isgenerated.IncaseinitializingobjectsisresponsibleforthirdpartylibrarieslikeSpringFramework,mostofthecasestheylookforno-argsconstructor. Followingexampledemonstrateshowyoucangenerateall-argsandno-argsconstructorwhenyouareusing@Dataand@Buildertogether. @AllArgsConstructor(access=AccessLevel.PACKAGE) @NoArgsConstructor @Data@Builder publicclassUser5{ privateLongid; privateStringusername; } Conclusion WehavecoveredinthisarticlewhatisLombokdataannotation(@Data),howdoweuseitinjavawithasimpleexamplebydifferentiatinglombokgeneratedcode.YoucanreferDelombokMavenexampletoseehowlookslikelombokgeneratedcodeforyourLombokedclasses. Lombokbeingamaturedtoolwithhugeadoption,itsavesasignificantamountofdevelopmenttimebygeneratingcommonlyusedboilerplatecodeforPOJOs,butittightlydependsonjavacompilerforannotationprocessing,youmustbeawarethatupgradingyourcompilermightbreakyourcode. Youcancheckoutsourcecodeatourgithubrepository. YoumightbeinterestedinourotherfollowingLombokTutorials: Lombok@Getter@SetterandlazygettersLombok@ToStringLombok@EqualsAndHashCodeLombok@AllArgsConstructorLombok@NoArgsConstructorLombok@RequiredArgsConstructorLombok@NonNullLombok@ValueLombok@BuilderLombok@Slf4jLombok@Singular reportthisad Lombok Tagsdatajavalombok PreviousarticleJavaTreeMapguidewithexamplesNextarticleSpringbootemailtemplatewithThymeleaf 1COMMENT HiSatishVarma, Youdidanexcellentjobonthispost!I’dliketoaddaquicknoteifyoudon’tmind? Wecan’tcreateaUser2objectasUser2z=newUser2(10,“Linda”)becausethereisnofieldonUser2classthatis“required”. Tomakesurethat@Datageneratesarequiredconstructor,weneedtomarkidandusernamewith@NonNullorfinal. Haveagreatday, Abderrahim Commentsareclosed. reportthisad reportthisad javabydeveloperJavaTutorials javabydeveloper.comjavabydeveloper.comistheindependentresourcebyenterpriseJavatechnologydevelopersfordeveloperswhowanttolearnaboutJavamostpopularandrelatedtechnologies.Ourprimarygoalistoprovidesimpleandeffectivetutorialswithwelltestedworkingexamplesforthealllevelofdevelopers. ©2015-2022javabydeveloper.com|Allrightsreserved DESCLAIMER Alltrademarksarethepropertyoftheirrespectiveowners,whichareinnowayassociatedwithjavabydeveloper.comjavabydeveloper.com.JavaisatrademarkorregisteredtrademarkofOracleCorporation.ExamplesatjavabydeveloperisnotconnectedtoOracleCorporationandisnotsponsoredbyOracleCorporation. ABOUTUS AboutUsPrivacyPolicyContactUsSiteMapCompanyInfo PopularCategories CoreJavaJPAHibernateJava8SpringBootJunit5LombokMaven xx
延伸文章資訊
- 1Stable - Project Lombok
Running delombok. Delombok copies your source files to another directory, replacing all lombok an...
- 2IT|軟體|開發|Lombok @Data - iT 邦幫忙
為了讓Eclipse識別lombok,除了引入lombok JAR包之外,你需要安裝lombok, ... Lombok 的特色是根據 annotation 創建一些程式碼,以減少重復程式碼的數...
- 3The Ultimate Lombok Annotations Guide | Nullbeans.com
The @Synchronized annotation is a method level annotation. According to Lombok, using this annota...
- 4Introduction to Project Lombok | Baeldung
By adding the @Getter and @Setter annotations, we told Lombok to generate these for all the field...
- 5@Data - Project Lombok
@Data is a convenient shortcut annotation that bundles the features of @ToString , @EqualsAndHash...