Is there a way to automatically generate getters and setters in ...

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

1) Press Alt + Shift + S , then R · 2) Right click -> Source -> Generate Getters & Setters · 3) Go to Source menu -> Generate Getters & Setters · 4) Go to Windows ... 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 IsthereawaytoautomaticallygenerategettersandsettersinEclipse? AskQuestion Asked 10years,6monthsago Modified 2yearsago Viewed 347ktimes 273 49 IamworkingonanewAndroidproject(Java),andcreatedanObjectwithalargenumberofvariables.SinceIamplanningtoaddgettersandsettersforallofthem,Iwaswondering:isthereashortcutinEclipseforautomaticallygeneratingthegettersandsettersinagivenclass? javaandroideclipsekeyboard-shortcuts Share Follow editedAug26,2019at16:43 mavis 2,81033goldbadges2121silverbadges3131bronzebadges askedAug28,2011at14:56 PhilPhil 34.9k2323goldbadges120120silverbadges158158bronzebadges 6 1 Soundslikeastalkertome...IjustusedtodoallJavaprogrammingwithoutanIDE,sousingEclipseisstillrelativelynewtome. – Phil Aug28,2011at15:20 3 @krio-Thewholeworlddoesn'tuseEclipseforJavadev.IdidmostofmyworkinIntelliJ,andfoundmyselfaskingalotofquestionslikethisonceIstartedworkinginEclipse. – vcsjones Aug28,2011at15:27 1 @Phil,vcsjones-verytruemyapologiesbutcheckthisout,-google.com.au/…-Iguessstackoverflowsaysresearchisimportant – TeaCupApp Aug28,2011at16:07 2 it'sfastestway:ctrl+3ggas – dellasavia Jan22,2015at0:21 1 @Konstantinthatjustsaystoavoidusingtheminthesameclass,sodon'tcallthis.getCount(),whenyoucanjustreferencethis.mCount.Althoughitmaybeamorecostlyoperation,itisacleanerapproachtoprovideaccesstovariablesofotherobjectsviagettersandsetters. – Phil Feb3,2015at22:45  |  Show1morecomment 19Answers 19 Sortedby: Resettodefault Highestscore(default) Datemodified(newestfirst) Datecreated(oldestfirst) 388 Bringupthecontextmenu(i.e.rightclick)inthesourcecodewindowofthedesiredclass.ThenselecttheSourcesubmenu;fromthatmenuselectingGenerateGettersandSetters...willcauseawizardwindowtoappear. Source->GenerateGettersandSetters... SelectthevariablesyouwishtocreategettersandsettersforandclickOK. Share Follow editedMar13,2020at19:59 mtotowamkwe 1,54511goldbadge99silverbadges1515bronzebadges answeredAug28,2011at14:58 HagaiCibulskiHagaiCibulski 4,24122goldbadges1818silverbadges2222bronzebadges 5 Thereisonly'GenerateElementComment',noGettersandSetters.I'musingEclipse4.4.0,PDTplugininstalled.Inmeantimethiscanbeused-mikeangstadt.name/projects/getter-setter-gen. – Xdg Aug11,2015at8:00 WorksgreatonEclipseMars.2Release(4.5.2).Thanks. – this.user3272243 Apr20,2016at7:57 14 YoucanalsoaccessthissubmenuwiththekeyboardshortcutSHIFT+ALT+S,andthenopentheGenerateGettersandSettersoptionsbypressingR. – Rosa Aug5,2016at14:39 Funnyhowmyanswerheregotsopopular,butthesedaysIwouldjustuseLombok,asnotedbyothersbelow. – HagaiCibulski Aug22,2018at12:53 YoucanalsouseCMD/CTRL-andstarttyping'get'or'set'andtheproposalwindowwilllistanymissinggetters/setters.Selecttheoneyouwanttoaddtheimplementation. – Kevin May15,2020at16:14 Addacomment  |  78 InEclipseJuno,bydefault,ALT+SHIFT+S,Ropensthegetter/setterdialogbox.Noteyouhavetopressall4keys. Share Follow answeredMar7,2013at18:03 RoboAlexRoboAlex 4,67666goldbadges2929silverbadges3737bronzebadges 5 6 YoucanleaveouttheSHIFTpartandjustdoALT+S,Raswell. – JasonWheeler Feb7,2014at23:42 2 YoucannotleaveoutSHIFTinEclipseKepler – yellavon Apr3,2014at18:20 YoucanleaveoutSHIFTinEclipseOxygen. – JakeReece Oct31,2018at13:24 YoucannnotleaveoutSHIFTinEclipse2018-12. – Neph Sep17,2019at11:25 InSpringToolSuite3-->ALT+SHIFT+S(waitforthemenutoopen)thenpressR – skarabel Jul1,2021at9:26 Addacomment  |  70 Rightclick->Source->Generatesettersandgetters Buttomakeitevenmoreconvenient,IalwaysmapthistoALT+SHIFT+GfromWindows->Preferences->General->Keys Share Follow editedMar2,2018at9:29 LYES-CHIOUKH 4,24588goldbadges3636silverbadges5353bronzebadges answeredAug28,2011at15:00 BozhoBozho 569k138138goldbadges10421042silverbadges11291129bronzebadges 0 Addacomment  |  46 AlltheotheranswersarejustfocusontheIDElevel,thesearenotthemosteffectiveandelegantwaytogenerategettersandsetters. Ifyouhavetensofattributes,therelevantgettersandsettersmethodswillmakeyourclasscodeveryverbose. ThebestwayIeverusedtogenerategettersandsettersautomaticallyisusingprojectlombokannotationsinyourjavaproject,lombok.jarwillgenerategetterandsettermethodwhenyoucompilejavacode. Youjustfocusonclassattributes/variablesnaminganddefinition,lombokwilldotherest.Thisiseasytomaintainyourcode. Forexample,ifyouwanttoaddgetterandsettermethodforagevariable,youjustaddtwolombokannotations: @Getter@Setter publicintage=10; Thisisequaltocodelikethat: privateintage=10; publicintgetAge(){ returnage; } publicvoidsetAge(intage){ this.age=age; } Youcanfindmoredetailsaboutlombokhere:ProjectLombok Share Follow editedFeb18,2016at2:36 answeredFeb18,2016at2:07 dongpfdongpf 1,4671616silverbadges88bronzebadges 2 1 That'sit!Thankyouverymuch!Actually,youranswershouldbeontop,sincelombokistheonlytruesolutiontoavoidseeingalltheboilerplateJavacodeonewouldhavetogenerateorwrite.Thanks! – StefanEndrullis Mar4,2016at14:01 2 ProjectLombok(oratleasttheidea)shouldbepartofJava11.IuseKotlinforPojoclassesonlytoescapegettersettergeneration:/ – Wolf359 Apr11,2018at22:01 Addacomment  |  32 WaystoGenerateGetters&Setters- 1)PressAlt+Shift+S,thenR 2)Rightclick->Source->GenerateGetters&Setters 3)GotoSourcemenu->GenerateGetters&Setters 4)GotoWindowsmenu->Preferences->General->Keys(WriteGenerateGetters&Settersontextfield) 5)Clickonerrorbulbofthefield->creategetters&setters... 6)PressCtrl+3andwritegetters&settersontextfieldthenselectoptionGenerateGetters&Setters ifMacOSpressAlt+cmd+SthenselectGetters&Setters Share Follow editedMar24,2017at10:26 answeredNov9,2014at12:55 DeepakGuptaDeepakGupta 1,0151414silverbadges1717bronzebadges 3 2 Ithinkthat1it'sabiteasierinthisway:1)PressAlt+Shift+S,thenR – PacoAbato Sep29,2015at9:24 1 PressingCtrl-3anddirectlyafterwardstyping"getter"ismissingfromthelist.Mucheasiertorememberthanspecificshortcuts,asthisworksforeverycommand,viewandsoon. – Bananeweizen Oct9,2015at5:50 @Bananeweizen-Thanks – DeepakGupta Mar13,2016at16:21 Addacomment  |  11 Rightclick->generategettersandsettersdoesthejobwellbutifyouwanttocreateakeyboardshortcutineclipseinwindows,youcanfollowthefollowingsteps: GotoWindow>Preferences GotoGeneral>Keys Listfor"QuickAssist-Creategetter/setterforfield" Inthe"Binding"textfieldbelow,holdthedesiredkeys(inmycase,IuseALT+SHIFT+G) HitApplyandOk NowinyourJavaeditor,selectthefieldyouwanttocreategetter/settermethodsforandpresstheshortcutyousetupinStep4.Hitokinthiswindowtocreatethemethods. Hopethishelps! Share Follow answeredFeb5,2013at19:35 sufinawazsufinawaz 3,47711goldbadge2424silverbadges2323bronzebadges Addacomment  |  9 Sure. UseGenerateGettersandSettersfromtheSourcemenuorthecontextmenuonaselectedfieldortype,oratextselectioninatypetoopenthedialog.TheGenerateGettersandSettersdialogshowsgettersandsettersforallfieldsoftheselectedtype.Themethodsaregroupedbythetype'sfields. Takealookatthehelpdocumentationformoreinformation. Share Follow answeredAug28,2011at14:59 vcsjonesvcsjones 133k3030goldbadges289289silverbadges278278bronzebadges Addacomment  |  8 Yes.Right-clickoncodeandyouseeamenupopup;there"Source","GenerateGettersandSetters"andnexttoityoucanseetheshortcut,whichisAlt+Shift+SandRonmysystem. Similarlyyoucannavigatetoothersubmenusinthatmainmenu,bytypingtheappropriateshortcutyougostraightthesubmenuinsteadofmaincontextmenu,andcantheneitherpickfrommenuortypeanotherlettertopickfromthelist. Share Follow answeredAug28,2011at15:01 ZdsZds 4,21122goldbadges2323silverbadges2828bronzebadges Addacomment  |  8 OnMacOSit'sAlt+Cmd+Sthenselect"...GettersandSetters" Share Follow answeredFeb21,2014at14:58 AlexanderVolkovAlexanderVolkov 7,26811goldbadge4444silverbadges4141bronzebadges Addacomment  |  7 Iprefertocreatetheprivatefieldfirst privateStringfield; Eclipsewillautohighlightthevariable,bypositioningcursoroveryournewvariable,pressCtrl+1.ItwillthengiveyouthemenutoCreategetterandsetter. IpressCtrl+1becauseitisabitmoreintelligentaboutwhatIthinkyouwantnext. Share Follow editedFeb25,2016at22:54 answeredMay30,2013at1:23 DavidChiewDavidChiew 57455silverbadges1313bronzebadges Addacomment  |  6 ForAllvariableALT+SHIFT+SThenRandforselectallPressALT+A ForSinglevariablePointcursoronthevariablethenpressCTRL+1andgoforthesecondoptionfromsuggestions Share Follow answeredApr17,2019at9:12 RohitMewadaRohitMewada 15611silverbadge22bronzebadges 0 Addacomment  |  5 PressAlt+Shift+S+R...andthenonlyselectwhichallfieldsyouhavetogenerateGettersorSettersorboth Share Follow answeredFeb21,2014at10:49 SagarSawantSagarSawant 6711silverbadge22bronzebadges 0 Addacomment  |  4 ThereisanopensourcejaravailableknowasLombok,youjustaddjarandthenannotateyourPOJOwith@Getter&@Setteritwillcreategettersandsettersautomatically. Apartfromthiswecanuseotherfeatureslike@ToString,@EqualsAndHashCodeandprettyothercoolstuffwhichremovesvanillacodefromyourapplication Share Follow editedMar10,2017at6:54 answeredAug5,2016at15:52 rajadilipkollirajadilipkolli 3,29411goldbadge2424silverbadges4646bronzebadges Addacomment  |  3 Eclipse>Source>GenerateGettersandSetters Share Follow answeredNov12,2013at7:48 user2332195user2332195 7144bronzebadges Addacomment  |  3 **InEclipseIde forgeneratingbothsettersandgetters->alt+shift+s+rthenAltAthenclickonok; forgeneratingonlygetters->alt+shift+s+rthenpressgthenclickonokbutton; forgeneratingonlysetters->alt+shift+s+rthenpresslthenclickonokbutton;** Share Follow answeredApr14,2016at9:51 abhinavabhinav 3111bronzebadge Addacomment  |  2 Rightclickonthepropertyyouwanttogeneratethegetterandsettersforandchoose Source->GenerateGettersandSetters... Share Follow answeredNov21,2014at20:27 EduardoDennisEduardoDennis 13k1313goldbadges7878silverbadges103103bronzebadges Addacomment  |  2 1)GotoWindows->Preferences->General->Keys 2)Selectthecommand"GenerateGettersandSetters" 3)IntheBinding,presstheshortcuttoliketouse(likeAlt+Shift+G) 4)Clickapplyandyouaregoodtogo Share Follow editedJan20,2016at13:05 BartoszFiryn 2,55422goldbadges2020silverbadges1818bronzebadges answeredDec29,2015at1:11 PrateekJoshiPrateekJoshi 3,68333goldbadges3737silverbadges5050bronzebadges Addacomment  |  1 OpentheclassfileinEclipse Doubleclickontheclassnameorhighlightit ThennavigatetoSource->InsertCode ClickonGetterandSetter Itopensapopuptoselectthefieldsforwhichgetter/settermethodstobegenerated.Selectthefieldsandclickon"Generate"button. Share Follow answeredJun4,2017at4:08 VallabhaVamaravelliVallabhaVamaravelli 98811goldbadge88silverbadges1515bronzebadges Addacomment  |  1 UseProjectLombokorbetterKotlinforyourPojos. (Also,toaddKotlintoyourresume;)) This: publicclassBaseVO{ protectedLongid; @Override publicbooleanequals(Objectobj){ if(obj==null||id==null) returnfalse; if(objinstanceofBaseVO) return((BaseVO)obj).getId().equals(id); returnfalse; } @Override publicinthashCode(){ returnid==null?null:id.hashCode(); } //gettersetterhere } publicclassSubclassextendsBaseVO{ protectedStringname; protectedStringcategory; //gettersetterhere } wouldbecomethis: openclassBaseVO(varid:Long?=null){ overridefunhashCode():Int{ if(id!=null) returnid.hashCode() returnsuper.hashCode() } overridefunequals(other:Any?):Boolean{ if(id==null||other==null||other!isBaseVO) returnfalse returnid.hashCode()==other.id?.hashCode() } } @Suppress("unused") classSubclass( varname:String?=null, varcategory:String?=null ):BaseVO() OruseKotlin's"data"classes.Youendupwritingevenfewerlinesofcode. Share Follow answeredApr11,2018at22:13 Wolf359Wolf359 2,34611goldbadge3232silverbadges5050bronzebadges Addacomment  |  Highlyactivequestion.Earn10reputation(notcountingtheassociationbonus)inordertoanswerthisquestion.Thereputationrequirementhelpsprotectthisquestionfromspamandnon-answeractivity. Nottheansweryou'relookingfor?Browseotherquestionstaggedjavaandroideclipsekeyboard-shortcutsoraskyourownquestion. TheOverflowBlog AIandnanotechnologyareworkingtogethertosolvereal-worldproblems FeaturedonMeta WhatgoesintositesponsorshipsonSE? StackExchangeQ&AaccesswillnotberestrictedinRussia AskWizardforNewUsersFeatureTestisnowLive NewUserExperience:DeepDiveintoourResearchontheStagingGround–How... Linked 0 Isthereafasterwaytosetmethodsineclipsewithjava? -1 Isthereawaytoautogenerateboilerplatecodeforpojomappingwithouthidingimplementationineclipse 4 GettersandSettersinJavaconvention 4 HowtogeneratecommentsaswellwhenautomaticallygeneratinggettersandsettersinAndroidStudio 2 Convert"autoproperty"inC#toJavaalternativecode 1 Returningmultipleintegersinonemethod 0 Howtoaccessavalueofaprivateinstancevariablefromadifferentclass? 0 Eclipse,shortwaytoinitializeobjectviasetters 1 returningmultipleseriesfrommethod 0 JavaValueofFieldNotUsed Seemorelinkedquestions Related 2088 IsthereawaytorunPythononAndroid? 1561 Fastestwaytodetermineifaninteger'ssquarerootisaninteger 1735 Whyusegettersandsetters/accessors? 1197 Which@NotNullJavaannotationshouldIuse? 396 Unabletoexecutedex:MultipledexfilesdefineLcom/myapp/R$array; 1066 AndroidStudio:Addjaraslibrary? 5 Eclipsegenerategettersandsettersandautomaticallyapplythem 798 Errorretrievingparentforitem:NoresourcefoundthatmatchesthegivennameafterupgradingtoAppCompatv23 HotNetworkQuestions Howwouldabeltsanderwingperform? Creatingalistofconditions Changetheradiusandresolutionofinstancedcirclesperinstance WhatisthegeographicallocationofPython(andotheropen-sourcesoftwareprojects)? Did"fossil-fuelpollution[kill]threetimesasmanypeopleasCOVID-19did"in2020? WhydoesAgustínsay"miércoles"intheEncantomovie?Whatdoesitmean? Howtomotivatestafftoattendapaidcertification? Howtogetthelistofconstanttermsoflinearequations? Whydoesn'ttheUSsendairplanestoUkraine,whenRussianssentMIGstoVietnamduringVietnamwar? Rationalfortuberculosisvaccines? WhydoAirForceplanesregularlyflyincircles? RecreateMinecraft'slighting Measuringdistancebetweenwaveylines/pointsinQGIS Howtomakeatranslucentmaterialthatlookslikethisaxolotltail? HowcanIfacilitateafasterpaceofplay? Separatingbusinesslogicfromdatatemptsmetouseinstanceof WhatdoestheLorentzfactorrepresent? FitdatawithNormalDistribution Isitimpolitetosendtheprofessorapre-writtenletterofrecommendationforapproval? InterpretationofasubtoureliminationconstraintintheTSP Inacyberpunkworldwherecorporateupperclasscitizenscanworkvirtuallythroughimplants,whywouldtheybuildcorporatemega-skyscrapers? HowDoesOrbitalWarfareWork? Derivingtheapparentangularspeedofastar HowcanIreplaceastringinatext? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-java Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?