Lombok how to customise getter for Boolean object field?

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

You have two options to override a Getter/Setter in your class. One is the answer from First Option response. The other option is to simply ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore LombokhowtocustomisegetterforBooleanobjectfield? AskQuestion Asked 8years,7monthsago Modified 1year,5monthsago Viewed 72ktimes 71 18 OneofmyPOJOshasaBooleanobjectfieldtopermitNULLSinthedatabase(arequirement).Isitpossibletousethe@DataLombokannotationatclasslevelyetoverridethegetterfortheBooleanfield?ThedefaultitgeneratesisgetXXXmethodfortheBooleanfield.IwishtooverrideitasisXXX()? Thanks, Paddy javalombok Share Follow editedSep29,2020at9:12 AbimaranKugathasan 28.6k1111goldbadges7070silverbadges102102bronzebadges askedAug9,2013at3:33 PaddyPaddy 3,11255goldbadges2828silverbadges4646bronzebadges 2 Bydefinition,overridingmeans,writingyourowngetXXXforthatprovidedbylombok.IfyouwanttoaddyourownisXXX,it'sadifferentmethod.Whydon'tyoucreateanisXXXinyourPOJOandintheimplementation,callgetXXXifrequiredorimplementitthewayyoulike? – Jayz Aug9,2013at4:07 Ihavedeclared@Dataatclasslevelandhavetoomanyattributesintheclass,soexcludinggetterormakingthedefaultgetterprivateforonefieldwillbetough.Otherwise,evenifIaddaisXXXmethod,thegetXXXmethodwillbestillvisibletousersoftheclassanyway-IwouldratherthenusethegetXXXmethoditself.Ihopeyouunderstandmycontext. – Paddy Aug9,2013at4:31 Addacomment  |  5Answers 5 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 122 It'sabitverbose,butyoucanprovideyourownisXXX,andthenuseAccessLevel.NONEtotellLomboknottogeneratethegetXXX: @Data publicclassOneOfPaddysPojos{ //...otherfields... @Getter(AccessLevel.NONE) privateBooleanXXX; publicBooleanisXXX(){ returnXXX; } } (Andhey,atleastit'snotquiteasverboseasifyouweren'tusingLomboktobeginwith!) Share Follow editedJul31,2019at17:09 answeredAug9,2013at4:07 ruakhruakh 165k2424goldbadges255255silverbadges292292bronzebadges Addacomment  |  17 IthinkifyouswitchyourfieldfromBooleanXtobooleanXthanlombokgenerateagetterisX()method. Share Follow answeredMar18,2016at14:36 katekate 1,64911goldbadge1010silverbadges1010bronzebadges 1 16 True,butyouneedtohavethefieldasaBooleanifthecolumnisnullableonthedatabaselevel.Theproblemisthatwithaprimitivefield(i.e.boolean)youcan'treallytellifacertainvalueissupposedtobeaNULLorazero(0).HenceOP'squestion. – PriiduNeemre Apr28,2016at7:44 Addacomment  |  8 IknowthequestionisoldbutIwillleavethisforfuturereferences. YouhavetwooptionstooverrideaGetter/Setterinyourclass. OneistheanswerfromFirstOptionresponse Theotheroptionistosimplydefinethegetter/settermethodandlombokwillnotautomaticallyproducethespecifiedmethod. Itesteditmyselfanditseemstoworkfine: @Data @AllArgsConstructor @NoArgsConstructor publicclassProductResponse{ privateUUIDid; privateStringsupplierId; privateStringsku; privateStringname; privateStringbrand; privateStringimgUrl; privateStringdescription; privateBigDecimalprice; privateFloatquantity; privateStringunit; //@Getter(AccessLevel.NONE)//Thismeans@Datawillnotproduceagetterforthisfieldsohavetoexplicitlydefineit privateSettags; //Hereweoverride@Datagetterwithadifferentgetter(returnisdifferenttype) publicListgetTags(){ returntags.stream().map(ProductTag::getId).collect(Collectors.toList()); } } Hereisalsoareferencefromthedevelopmentteamcomments:Lombok'sdevelopercomment InmyexampleI'musingthe"override"featureforaCollectiontypebutthiscanbeusedforanyothertypelikeBooleaninyourcase. Share Follow answeredMay2,2018at8:41 RafaelR.S.RoblesRafaelR.S.Robles 77266silverbadges1919bronzebadges 2 4 Inyourcaseit"works"becausethenameofyourcustomgettermatchesthenamethatlombokissupposedtogenerate.OPaskswhattodoifthenamedoesn'tmatch.IntheircasetheyareisXXX()andgetXXX(). – SashaShpota Dec27,2018at14:01 Goodcatch!ThanksforhighlightingthiswhichIoverlookedinthequestion. – RafaelR.S.Robles Jan4,2019at9:49 Addacomment  |  2 whatisthenameofbooleanfield?accordingtothelombokdoc: Adefaultgettersimplyreturnsthefield,andisnamedgetFooifthe fieldiscalledfoo(orisFooifthefield'stypeisboolean) lombokwillgenerategetterwithnameisXXXforyourbooleanfield Share Follow answeredAug9,2013at3:54 SeptemSeptem 3,56411goldbadge1919silverbadges1919bronzebadges 1 13 Youseemtobeconfused.TheOPisobviouslyawarethatabooleanfield'sgetterwillbenamedisXXX()bydefault;theproblemisthat(s)hewantsthatnamingconventiontobeusedforaBooleanfield(Booleanbeingtheobjectwrappertypeforboolean,likewhatIntegeristoint).(Thepagethatyoulinktoactuallystatesthisexplicitly:"Anyvariationonbooleanwillnotresultinusingtheisprefixinsteadofthegetprefix;forexample,returningjava.lang.Booleanresultsinagetprefix,notanisprefix.") – ruakh Aug9,2013at3:59 Addacomment  |  1 FromLombokdocumentation: Youcanalwaysmanuallydisablegetter/settergenerationforanyfieldbyusingthespecialAccessLevel.NONEaccesslevel.Thisletsyouoverridethebehaviourofa@Getter,@Setteror@Dataannotationonaclass. Share Follow answeredJan15,2020at8:38 GeorgeKargakisGeorgeKargakis 3,87322goldbadges1414silverbadges1212bronzebadges Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedjavalombokoraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia Shouldweburninatethe[term]tag? NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... AskWizardforNewUsersFeatureTestisnowLive Linked 25 Editlombokgettermethodnameforbooleanmemberhavingprefix"has" 18 HowtooverrideLombokSettermethods 1 WhyitgiveserrorifItrytogetthevalueofaboolean@Transientvariableusinglombok? -2 Can'toverrideLombokgetter Related 1634 HowdoestheJava'foreach'loopwork? 319 OmittingoneSetter/GetterinLombok 6 PropertyUtilsfailedtoconvertbooleanifthegetteruses"is"ratherthan"get" 2 Sonar"SingularField"rulecontradictslombok-getter 0 Eclipsecodeassistdoesn'tproposebooleanjavabeangetter 42 Lombokannotation@Getterforbooleanfield 15 [email protected] 2 IntellijdoesnotseeusageofLombokgetterinimplementationclass HotNetworkQuestions Depassivavocecumverbisquaecasumdativumpostulant Decidingwhetheranintegerpolynomialhasanintegerroot Wouldwearingfullplatearmorcauseslashingdamagetobeconvertedintobludgeoningdamage? Rationalfortuberculosisvaccines? My(manual)transmissionwon'tengageanygear1dayafterescapingbog Combineeachelementwithalltheothersinsublists Woulditbepossibleforoneairlinertotowanother? Howdoestheprincipleofrelativityimplythatphotonclocksandmechanicalclocksexperiencetimedilationthesameway? ArticleorRelativePronoun Howtomotivatestafftoattendapaidcertification? FitdatawithNormalDistribution IsareturnairticketabsolutelynecessaryforaSchengenbusinesstrip? Willunevenspeedberoundedupordown? Typingabashcommand,I'matitsthirdline.ButhowdoIreturntoitsbeginningtoeditsomethingI'vemissed? IfplayerAisincheckbuthasamovewhichwillcheckmateplayerBwithoutexitingcheck,isthatmovelegal? Retainingambitiousemployeewithrareskillset Jacobianmatrixevaluationatapoint WhatdoestheLorentzfactorrepresent? Howdoeslicensingsoftwarenotimplyownership?Don'tIownaWindowsoperatingsystemonceIpayforit? Whatpeople,ifany,pushedPutinintothewarwithUkraine? Whyarerealphotonssomuchlessefficientincarryingmomentumthanvirtualphotons? HowdoyouexplainCanada'sTrudeau'spower-sharingagreementtoafive-year-old(American)? IsthisUrsineplayerracebalanced? Minussignnotaligningwithfraction morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-java Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?