Say “bye bye!!!”​ to Annoying Getters/Setters & Shorten your ...

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

When you annotate your Entity class with @Getter and @Setter , it will generate getter methods and setter methods for all the fields in your ... UpgradeOpeninappHomeNotificationsListsStoriesWriteSay“byebye!!!”​toAnnoyingGetters/Setters&ShortenyourJavaCodewith`​lombok`​Still,therearethingsthataJavaprogrammerhastodooverandoveragainjusttogetthecodecompletefromlanguage/syntaxpoint-of-viewratherthanspendingtimeonbusinesslogic,theactualtaskathand.Havingtowriteorevenauto-generateGetters,Setters,customConstructorsandcustomtoStringmethodinPOJOsisonesuchissue.Asasolutionforthiscumbersomeproblem,ProjectLombokhasquiteelegantlyaddressedthisissue.First,justneedtoaddthelombokdependencytoyourprojectandthenusetheavailableannotationsappropriately.InyourSpringbootproject,gotopom.xmlfileandaddthebelowdependencywithinthetagsorg.projectlomboklomboktrue1.18.8Checkforthemostrecentavailableversionhere.**Forthelatestlombok.jarfile**1.0AnnotationsAvailableforUseLombokprojectprovidesuswithseveralannotationstoavoidboilerplatecodesinourentityclass.Givenbelowisalistoftheavailableannotationsandsomeveryessentialsetoftheannotationswillbediscussedbrieflywithexamples.AnnotationList@Getter@Setter@Builder@NonNull@Data@ToString@Getter(lazy=true)@AllArgsConstructor@NonNull@EqualsAndHashCode@NoArgsConstructor@Value@Log@Synchronized@RequiredArgsConstructor@SneakyThrows@[email protected]@[email protected]===================================================================================*******************************====================@Getter/@SetterWhenyouannotateyourEntityclasswith@Getterand@Setter,itwillgenerategettermethodsandsettermethodsforallthefieldsinyourclass.Or,youcanplacethesetwoannotationsseparatelybeforethenecessaryfields(Notbeforetheclassname),whenyoudon’tneedgettingandsettingmethodsforallthefieldsavailable.@NoArgsConstructorWhenyouplacethisconstructorbeforetheclassname,thiswillcreateaconstructorwithoutanyargumentsinit.(anemptyconstructor)Thisannotationisusefulprimarilyincombinationwitheither@Dataoroneoftheotherconstructorgeneratingannotations.@AllArgsConstructorThisannotationwhenplacebeforetheclassname,generatesaconstructortakingallthefieldsasargumentsinit.@NonNullYoucanuse@NonNullontheparameterofamethodorconstructortohavelombokgenerateanull-checkstatementforyou.(Seebelowcodeexamples)##Using@NonNullannotation##packagecom.udith.articles.lombokDemo.entities;importcom.udith.articles.lombokDemo.entities.Person;importjava.io.Serializable;importlombok.NonNull;publicclassStudentextendsSerializable{privateStringname;publicStudent(@NonNullPersonperson){super("Hello");this.name=person.getName();}}##Whenlombokgeneratesthecodefortheabovesnippet,thecodelookslikethis##packagecom.udith.articles.lombokDemo.entities;importcom.udith.articles.lombokDemo.entities.Person;importjava.io.Serializable;importlombok.NonNull;publicclassStudentextendsSerializable{privateStringname;publicStudent(@NonNullPersonperson){super("Hello");if(person==null){thrownewNullPointerException("personismarked@NonNullbutisnull");}this.name=person.getName();}}Further,youcanannotatethefieldsinanentityclasssothatthosemarkedfieldswillbeusedforcreatingconstructorwiththeannotations@Dataand@RequiredArgsConstructor.@RequiredArgsConstructor@RequiredArgsConstructorgeneratesaconstructorwithparametersforthefieldsthatrequiresspecialhandling.Allnon-initializedfinalfieldsgetaparameter,aswellasanyfieldsthataremarkedas@NonNullthataren’tinitializedwheretheyaredeclared.Seethecodesnippetbelow.Thecommentedpartshowsthelombokgeneratedconstructor.Whenthisannotationgeneratestheconstructor,theparametersincludedareorderedinthewaythecorrespondingfieldsareordered.@ToStringThisisalsoaveryusefulannotationindebuggingetc.Anyclassdefinitionmaybeannotatedwith@ToStringtoletlombokgenerateanimplementationofthetoString()method.Bydefault,it’llprintyourclassname,alongwitheachfield,inorder,separatedbycommas.@ToStringannotationbydefaultimplies@ToString(includeFieldNames=true).But,bychangingitsabovepropertytofalse,astringwithoutfields’namescanbereturned.Further,wecancustomizethefieldsthatweneedtoexcludeandincludetotheToString()method.Thiscanbeachievedintwoways.1)[email protected]@ToStringannotation.Justadd@ToString.Excludeannotationbeforethefieldsthatyouneedtoexcludefromthereturnedstring.(Seetheexampleright).2)[email protected]@ToString(onlyExplicitlyIncluded=true)annotation.Afteradding@ToString(onlyExplicitlyIncluded=true)beforetheclass,[email protected],onlythoserequiredfieldswillbeincludedinthereturnedstring.@EqualsAndHashCodeWhenplacedbeforeaclassdeclaration,thisannotationimplementspublicbooleanequals(Objectobj){}methodforallthefieldsandpublicinthashCode(){}methodforallthefields.Youcanexcludeanyfieldthatneedn’ttobeinsertedinthegeneratedtwomethods,simplybyplacing@EqualsAndHashCode.Excludeannotationoverthefieldyouneedtoexclude.**[Or,youcanexplicitlyincludetherequiredfieldsforthesetwomethodsbyreplacing@EqualsAndHashCodewith@EqualsAndHashCode(onlyExplicitlyIncluded=true)beforetheclassdeclarationandthenplacing@EqualsAndHashCode.Includeovertherequiredfields.]**@DataThisisaveryconvenientshortcutkeythatbundlesthefeaturesof@ToString,@EqualsAndHashCode,@Getter/@Setterand@RequiredArgsConstructortogether.packagecom.udith.lombokdemo.entities;importjava.io.Serializable;importjava.util.Date;importjava.util.Objects;importjavax.persistence.Entity;importjavax.persistence.Id;importlombok.Data;@Entity@DatapublicclassStudentimplementsSerializable{@Idprivatelongid;privateintage;privateDatebirthday;}===================*******************************==================================================================================Aboveexplainedareonlysomefrequentlyusedannotations,butyoucanhandlethemsmootherasyourequirewithlombok.Youcanfindmorefeatureshere.~~UdithIndrakantha~~MorefromUdithGayanIndrakanthaFollowTechnologyEnthusiast|FullStackwebDeveloper|https://udith.netlify.comLovepodcastsoraudiobooks?Learnonthegowithournewapp.TryKnowableMorefromMediumCommunicationbetweenmultipledocker-composeprojectsValidationafteruploadingaJSONLinesfileJSONLinesisaconvenientformatforstoringstructureddatathatmaybeprocessedonerecordatatime.Itessentiallyconsistsof…HowToCreateAnAwesomeGitHubProfileReadmeAPostmanCollectionforTrainingIBMWatsonSpeechtoTextMVVM,RoomDatabaseWithKotlinCoroutainsTheRoompersistencelibraryprovidesanabstractionlayeroverSQLitetoallowfluentdatabaseaccesswhileharnessingthefullpowerof…EvernoteIsDead,LongLiveNotionHowIfinallygaveuponEvernoteandfellinlovewithNotion.MakingaDynamicRecyclerViewAdapterthatworkslikemagicThisIsTheOldestPythonProjectOnGitHubWelcomeback!Recently,i’vebeengoingthroughatonofdifferentprojectsonGithub,it’ssointerestingtoseewhatotherpeoplehave…GetstartedUdithGayanIndrakantha153FollowersTechnologyEnthusiast|FullStackwebDeveloper|https://udith.netlify.comFollowRelatedDynamicallyroutetoread-onlyandread-writedatabaseinstancesinspring-bootSpringBootStarterInthispostwewillseehowSpringBootstartersworkandwewillcreateabasicexampleusingWebClient.HowtoFixIfJavainheritanceisnotworkingJava8lambdafunctionimplementsdeduplicationoflistsbasedonpropertyvaluesHelpStatusWritersBlogCareersPrivacyTermsAboutKnowable



請為這篇文章評分?