Lombok @Getter @Setter and lazy getters examples

文章推薦指數: 80 %
投票人數:10人

This lets you override the behavior of a @Getter , @Setter or @Data annotation on a class. Lobmoked User.java. @Getter. 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 HomeLombokLombok@Getter@Setterandlazygettersexamples Lombok@Getter@Setterandlazygettersexamples BySatishVarma August11,2020 CompleteguidetoexplaintheusageofLombok@Getter,@Setterannotationsandgeneratinglazygetterswithseveralexamples. TableofContent  [hide]1.AnnotatingFieldswith@[email protected]@Getterand@Setter3.Changingaccesslevelforgeneratedgettersandsetters4.ExcludeOrdisablegeneratinggetters/setters5.ReturnOptionalforGetter6.Getterforbooleanfileds7.ReturnthisforSetters8.GenerateLazyGetter9.PutAnnotationsonLombokgeneratedConstructors,methodsandparameters10.Conclusion 1.AnnotatingFieldswith@Getterand@Setter AnnotateanyfieldwithLombok’s@Getterand@Settertogeneratethedefaultgetter/setterautomaticallybyLombok.Thegeneratedgetter/settermethodwillbe public bydefault.Let’sseethefollowingsidebysideexamples,therightsideexampleisthedelombokedjavacodefortheleftsidejavacode. MakesureyoualreadyinstalledLomboksetupforyourIDE.ToSetupinEclipseorinSpringToolSuiterefertoourLombokMavenexamplesetupwithEclipse. LobmokedUser.java publicclassUser{ @Getter privateLongid; @Setter privateStringusername; @Getter@Setter privateStringemail; @Getter@Setter privateLocalDatelastUpdated; } DelombokedUser.Java //GeneratedbydelombokatTueMar3116:03:35SGT2020 packagecom.javabydeveloper.lombok.settergetter; importjava.time.LocalDate; publicclassUser{ privateLongid; privateStringusername; privateStringemail; privateLocalDatelastUpdated; publicStringgetUsername(){ returnthis.username; } publicvoidsetId(finalLongid){ this.id=id; } publicLonggetId(){ returnthis.id; } publicvoidsetUsername(finalStringusername){ this.username=username; } publicStringgetEmail(){ returnthis.email; } publicvoidsetEmail(finalStringemail){ this.email=email; } publicLocalDategetLastUpdated(){ returnthis.lastUpdated; } publicvoidsetLastUpdated(finalLocalDatelastUpdated){ this.lastUpdated=lastUpdated; } } 2.AnnotatingClasswith@Getterand@Setter Youcanalsoputa @Getter and/or @Setter annotationonaclass.Inthiscase gettersandsetterswillbegeneratedforallnon-staticfields.Nosettersandgettersgenerateforstaticfields.Nosetterswillbegeneratedforfinalfields. LobmokedUser.java @Getter @Setter publicclassUser{ privateLongid; privateStringusername; privateLocalDatelastUpdated; //nogettersettergeneratedforstaticfields publicstaticintmaxAge=40; //onlygetterswillbegeneratedforfinalfields publicfinalintminAge=20; } DelombokedUser.Java publicclassUser{ privateLongid; privateStringusername; privateLocalDatelastUpdated; //nogettersettergeneratedforstaticfields publicstaticintmaxAge=40; //onlygetterswillbegeneratedforfinalfields publicfinalintminAge=20; publicLonggetId(){ returnthis.id; } publicStringgetUsername(){ returnthis.username; } publicLocalDategetLastUpdated(){ returnthis.lastUpdated; } publicintgetMinAge(){ returnthis.minAge; } publicvoidsetId(finalLongid){ this.id=id; } publicvoidsetUsername(finalStringusername){ this.username=username; } publicvoidsetLastUpdated(finalLocalDatelastUpdated){ this.lastUpdated=lastUpdated; } } 3.Changingaccesslevelforgeneratedgettersandsetters Bydefaultgeneratedgetter/settermethodwillbe public.Tochangeaccessmodifierofgeneratedgettersandsetters,youneedtospecifyAccessLevelasshowninthefollowingexample.Thelegalaccesslevelsare PUBLIC, PROTECTED, PACKAGE,and PRIVATE. LobmokedUser.java @Getter @Setter publicclassUser{ @Setter(AccessLevel.PRIVATE) privateLongid; @Getter(AccessLevel.PROTECTED) privateStringusername; @Getter(AccessLevel.PACKAGE) privateStringemail; @Getter(AccessLevel.PUBLIC) @Setter(AccessLevel.PRIVATE) privateLocalDatelastUpdated; } DelombokedUser.Java publicclassUser{ privateLongid; privateStringusername; privateStringemail; privateLocalDatelastUpdated; publicLonggetId(){ returnthis.id; } publicvoidsetUsername(finalStringusername){ this.username=username; } publicvoidsetEmail(finalStringemail){ this.email=email; } privatevoidsetId(finalLongid){ this.id=id; } protectedStringgetUsername(){ returnthis.username; } StringgetEmail(){ returnthis.email; } publicLocalDategetLastUpdated(){ returnthis.lastUpdated; } privatevoidsetLastUpdated(finalLocalDatelastUpdated){ this.lastUpdated=lastUpdated; } } 4.ExcludeOrdisablegeneratinggetters/setters Youcanalwaysmanuallydisablegetter/settergenerationforanyfieldbyusingthespecial AccessLevel.NONE accesslevel.Thisletsyouoverridethebehaviorofa @Getter, @Setter or @Data annotationonaclass. LobmokedUser.java @Getter @Setter publicclassUser{ @Setter(AccessLevel.NONE) privateLongid; @Getter(AccessLevel.NONE) privateStringusername; privateStringemail; privateLocalDatelastUpdated; } DelombokedUser.Java publicclassUser{ privateLongid; privateStringusername; privateStringemail; privateLocalDatelastUpdated; publicLonggetId(){ returnthis.id; } publicStringgetEmail(){ returnthis.email; } publicLocalDategetLastUpdated(){ returnthis.lastUpdated; } publicvoidsetUsername(finalStringusername){ this.username=username; } publicvoidsetEmail(finalStringemail){ this.email=email; } publicvoidsetLastUpdated(finalLocalDatelastUpdated){ this.lastUpdated=lastUpdated; } } 5.ReturnOptionalforGetter SometimesyoumaywanttoreturnOptionalforyouroneofgettermethod,butyoudon’twanttogeneratesettertosetOptionalforthesamefield.InfollowingexampleLombokwon’tgenerategettermethod,writingyourowngetterimplementationforcestoLomboknottogenerateit’sown. LobmokedUser.java @Getter @Setter publicclassUser{ privateLongid; privateStringusername; privateStringemail; publicOptionalgetEmail(){ returnOptional.ofNullable(email); } } DelombokedUser.Java publicclassUser{ privateLongid; privateStringusername; privateStringemail; publicOptionalgetEmail(){ returnOptional.ofNullable(email); } publicLonggetId(){ returnthis.id; } publicStringgetUsername(){ returnthis.username; } publicvoidsetId(finalLongid){ this.id=id; } publicvoidsetUsername(finalStringusername){ this.username=username; } publicvoidsetEmail(finalStringemail){ this.email=email; } } 6.Getterforbooleanfileds FollowingexampledemonstrateshowLombokgeneratesgetters/settersforboolean/Booleanfields.BydefaultLombokgeneratesprefixisforgettersforbooleanfields.Tochangethisbehavior,setpropertyinlombokpropertieslombok.getter.noIsPrefix =true(default:false) LobmokedUser.java @Getter @Setter publicclassUser{ privateLongid; privateStringusername; privatebooleanactive; privatebooleanadmin; /*conflictforlombokhavingadminandisAdmin. *Lombokgeneratesonlyoneaccessorforfirstdeclaration */ privatebooleanisAdmin; //LombokgeneratesgetCitizenOfUS() privateBooleancitizenOfUS; } DelombokedUser.Java publicclassUser{ privateLongid; privateStringusername; privatebooleanactive; privatebooleanadmin; /*conflictforlombokhavingadminandisAdmin. *Lombokgeneratesonlyoneaccessorforfirstdeclaration */ privatebooleanisAdmin; //LombokgeneratesgetCitizenOfUS() privateBooleancitizenOfUS; publicLonggetId(){ returnthis.id; } publicStringgetUsername(){ returnthis.username; } publicbooleanisActive(){ returnthis.active; } publicbooleanisAdmin(){ returnthis.admin; } publicBooleangetCitizenOfUS(){ returnthis.citizenOfUS; } publicvoidsetId(finalLongid){ this.id=id; } publicvoidsetUsername(finalStringusername){ this.username=username; } publicvoidsetActive(finalbooleanactive){ this.active=active; } publicvoidsetAdmin(finalbooleanadmin){ this.admin=admin; } publicvoidsetCitizenOfUS(finalBooleancitizenOfUS){ this.citizenOfUS=citizenOfUS; } } 7.ReturnthisforSetters Sometimesyoumaywanttoreturncurrentinstance,inthiscaseeitheryouneedwritesettermanuallyorhavetoenablefluentaccessorforthefieldlikefollowingexample. LobmokedUser.java @Getter @Setter publicclassUser{ privateLongid; privateStringusername; //returnsthisforsetter @Accessors(fluent=true) privateStringemail; //usercreatedsetter publicUsersetUsername(StringuserName){ this.username=userName; returnthis; } } DelombokedUser.Java publicclassUser{ privateLongid; privateStringusername; //returnsthisforsetter privateStringemail; //usercreatedsetter publicUsersetUsername(StringuserName){ this.username=userName; returnthis; } publicLonggetId(){ returnthis.id; } publicStringgetUsername(){ returnthis.username; } publicbooleanemail(){ returnthis.email; } publicvoidsetId(finalLongid){ this.id=id; } publicUseremail(finalbooleanemail){ this.email=email; returnthis; } } 8.GenerateLazyGetter Ifyouuse@Getter(lazy=true)forthefield,initializationofthevaluewillbedelayeduntilthegettermethodiscalledfirstandvaluewillbecacheduponfirstcallandthecachedresultswillbereturnforthesubsequentcalls.Thefieldmustbeprivateandfinal.Followingexampledemonstrateshow@Getter(lazy=true)works. publicclassPayment{ @Getter privateLongid; @Getter privateStringstatus=simpleDefaultStatus(); @Getter(lazy=true) privatefinaldoublesurCharge=complexSurchargeLogic(); privatedoublecomplexSurchargeLogic(){ Doublesurcharge=Math.PI; System.out.println("CalledLazygetSurchargemethod"); returnsurcharge; } privateStringsimpleDefaultStatus(){ System.out.println("CalledEAGERgetStatusmethod"); return"NOT_INITIALIZED"; } } Testing: publicclassGetterLazyDemo{ publicstaticvoidmain(String[]args){ Paymentpayment=newPayment(); System.out.println("Eagergetterscalledatinstancecreationtime!"); doublesc=payment.getSurCharge(); } } Output: CalledEAGERgetStatusmethod Eagergetterscalledatinstancecreationtime! CalledLazygetSurchargemethod LombokGenerated/delombokedPayment.java: publicclassPayment{ privateLongid; privateStringstatus=simpleDefaultStatus(); privatefinaljava.util.concurrent.atomic.AtomicReferencesurCharge=newjava.util.concurrent.atomic.AtomicReference(); privatedoublecomplexSurchargeLogic(){ Doublesurcharge=Math.PI; System.out.println("CalledLazygetSurchargemethod"); returnsurcharge; } privateStringsimpleDefaultStatus(){ System.out.println("CalledEAGERgetStatusmethod"); return"NOT_INITIALIZED"; } publicLonggetId(){ returnthis.id; } publicStringgetStatus(){ returnthis.status; } publicdoublegetSurCharge(){ Objectvalue=this.surCharge.get(); if(value==null){ synchronized(this.surCharge){ value=this.surCharge.get(); if(value==null){ finaldoubleactualValue=complexSurchargeLogic(); value=actualValue; this.surCharge.set(value); } } } return(Double)value; } } 9.PutAnnotationsonLombokgeneratedConstructors,methodsandparameters Toputannotationsonthegeneratedmethod,youcanuseonMethod,onParamandonConstructorattributesfor@Getter,@Setter,@AllArgsConstructorand@NoArgsConstructorlikefollowingexample. LobmokedUser.java @Getter @Setter @AllArgsConstructor( onConstructor_=@ConstructorParameters({"id","email"})) publicclassUser{ privateLongid; //@Getter([email protected]__(@Deprecated))--JDK7 @Getter(onMethod_=@Deprecated)//JDK8 @Setter(onParam_=@NonFinal) privateStringemail; @Getter(onMethod_={ @Generated("com.javabydeveloper.lombok.settergetter.User"), @Deprecated }) privatebooleanactive; } DelombokedUser.Java publicclassUser{ privateLongid; //@Getter([email protected]__(@Deprecated))--JDK7 //JDK8 privateStringemail; privatebooleanactive; publicLonggetId(){ returnthis.id; } publicvoidsetId(finalLongid){ this.id=id; } publicvoidsetActive(finalbooleanactive){ this.active=active; } @ConstructorParameters({"id","email"}) publicUser(finalLongid,finalStringemail,finalbooleanactive){ this.id=id; this.email=email; this.active=active; } @Deprecated publicStringgetEmail(){ returnthis.email; } publicvoidsetEmail(@NonFinalfinalStringemail){ this.email=email; } @Generated("com.javabydeveloper.lombok.settergetter.User") @Deprecated publicbooleanisActive(){ returnthis.active; } } 10.Conclusion WehavecoveredmostoftheusecasesofLombokgetterandsetterannotations.AlsocoveredLombokgetterwithlazyinitialization.YoucanreferDelombokMavenexampletoseehowlookslikelombokgeneratedcodeforyourLombokedclasses. Youcancheckoutsourcecodeatgithub. YoumightbeinterestedinourotherfollowingLombokTutorials: Lombok@ToStringLombokDataLombok@ValueLombok@BuilderLombok@NonNullLombok@Slf4jLombok@SingularLombokSpringBootExample reportthisad Lombok Tags@getter@setterlombok PreviousarticleHowtogetcurrentDateTimeinjava8NextarticleLombok@NoArgsConstructorexamples LEAVEAREPLYCancelreply Comment: Pleaseenteryourcomment! Name:* Pleaseenteryournamehere Email:* Youhaveenteredanincorrectemailaddress! Pleaseenteryouremailaddresshere Website: Savemyname,email,andwebsiteinthisbrowserforthenexttimeIcomment. reportthisad reportthisad javabydeveloperJavaTutorials javabydeveloper.comjavabydeveloper.comistheindependentresourcebyenterpriseJavatechnologydevelopersfordeveloperswhowanttolearnaboutJavamostpopularandrelatedtechnologies.Ourprimarygoalistoprovidesimpleandeffectivetutorialswithwelltestedworkingexamplesforthealllevelofdevelopers. ©2015-2022javabydeveloper.com|Allrightsreserved DESCLAIMER Alltrademarksarethepropertyoftheirrespectiveowners,whichareinnowayassociatedwithjavabydeveloper.comjavabydeveloper.com.JavaisatrademarkorregisteredtrademarkofOracleCorporation.ExamplesatjavabydeveloperisnotconnectedtoOracleCorporationandisnotsponsoredbyOracleCorporation. ABOUTUS AboutUsPrivacyPolicyContactUsSiteMapCompanyInfo PopularCategories CoreJavaJPAHibernateJava8SpringBootJunit5LombokMaven xx



請為這篇文章評分?