Introduction to Project Lombok in Java and How to get started?

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

Project Lombok is a java library tool that is used to minimize/remove the boilerplate code and save the precious time of developers during ... Skiptocontent TutorialsPracticeDS&Algo.MustDoQuestionsDSATopic-wiseDSACompany-wiseAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsGeekontheTopCareersInternshipJobsApplyforJobsPostaJobJOB-A-THONEventsCourses ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningWebDevelopmentSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesTreeTraversals(Inorder,PreorderandPostorder)WhatisMemoryLeak?Howcanweavoid?SQL|Join(Inner,Left,RightandFullJoins)findcommandinLinuxwithexamplesCommonlyAskedDataStructureInterviewQuestions|Set1AnalysisofAlgorithms|Set1(AsymptoticAnalysis)AnalysisofAlgorithms|Set3(AsymptoticNotations)HowtowriteaPseudoCode?Understanding"extern"keywordinCAnalysisofAlgorithms|Set2(Worst,AverageandBestCases)MutexvsSemaphoreSQL|GROUPBYAnalysisofAlgorithms|Set4(AnalysisofLoops)SQL|ViewsRecursivePracticeProblemswithSolutionsSQLInterviewQuestionsLittleandBigEndianMysteryNP-Completeness|Set1(Introduction)StorageforStringsinCRecursiveFunctionsSQL|INSERTINTOStatementOOPs|ObjectOrientedDesignRunningPythonscriptonGPU.ExtendsvsImplementsinJavagetch()functioninCwithExamplesSQL|Join(CartesianJoin&SelfJoin)StructureMemberAlignment,PaddingandDataPackingJavaTutorialWhatisMemoryLeak?Howcanweavoid?SQL|UPDATEStatementTableofContentsTreeTraversals(Inorder,PreorderandPostorder)WhatisMemoryLeak?Howcanweavoid?SQL|Join(Inner,Left,RightandFullJoins)findcommandinLinuxwithexamplesCommonlyAskedDataStructureInterviewQuestions|Set1AnalysisofAlgorithms|Set1(AsymptoticAnalysis)AnalysisofAlgorithms|Set3(AsymptoticNotations)HowtowriteaPseudoCode?Understanding"extern"keywordinCAnalysisofAlgorithms|Set2(Worst,AverageandBestCases)MutexvsSemaphoreSQL|GROUPBYAnalysisofAlgorithms|Set4(AnalysisofLoops)SQL|ViewsRecursivePracticeProblemswithSolutionsSQLInterviewQuestionsLittleandBigEndianMysteryNP-Completeness|Set1(Introduction)StorageforStringsinCRecursiveFunctionsSQL|INSERTINTOStatementOOPs|ObjectOrientedDesignRunningPythonscriptonGPU.ExtendsvsImplementsinJavagetch()functioninCwithExamplesSQL|Join(CartesianJoin&SelfJoin)StructureMemberAlignment,PaddingandDataPackingJavaTutorialWhatisMemoryLeak?Howcanweavoid?SQL|UPDATEStatementImproveArticle SaveArticle LikeArticle IntroductiontoProjectLombokinJavaandHowtogetstarted?DifficultyLevel: EasyLastUpdated: 24May,2021Javaisaverypopularlanguage,butithasfewdrawbacks.Oneofthemostpopulardrawbacksisthatwestillneedtowritetheboilerplatecodeslikegetters,setters,toStringmethodinJavawhereasKotlinandScala,whicharealsoJVMbaseddon’tneedsoandhence,thisisthereasonfortheirincreasedpopularityinthecommunity.ThisiswhereLombokcomesintothepictureandovercomesthisdrawbackofJava. ProjectLombokisajavalibrarytoolthatisusedtominimize/removetheboilerplatecodeandsavetheprecioustimeofdevelopersduringdevelopmentbyjustusingsomeannotations.Inadditiontoit,italsoincreasesthereadabilityofthesourcecodeandsavesspace.Butyoumightbethinkingthatnowadays,everyoneusesIDEswhichprovidesanoptionforgeneratingtheseboilerplatecodes,thenwhatistheuseofLombok.WheneverweuseIDEstogeneratetheseboilerplatecodes,wejustsaveourselvesfromwritingallthesecodesbutitisactuallypresentinoursourcecodeandincreasestheLOC(linesofcode),andreducesmaintainabilityandreadability.Ontheotherhand,Lombokaddsalltheseboilerplatecodesatthecompile-timeinthe“.class”fileandnotinoursourcecode. LetuscompareoursourcecodewithandwithoutusingLombok. 1.WithoutLombok:Ajavamodelclasswithfourprivatefieldsandtheirgetters,setters,no-argsconstructor,parameterizedconstruct,andtoStringmethod. JavapublicclassEmployee{     privateIntegeremployeeId;    privateStringname;    privateStringcompany;    privateStringemailId;     publicEmployee(){}     publicEmployee(IntegeremployeeId,Stringname,                    Stringcompany,StringemailId)    {        super();        this.employeeId=employeeId;        this.name=name;        this.company=company;        this.emailId=emailId;    }     publicIntegergetEmployeeId(){returnemployeeId;}     publicvoidsetEmployeeId(IntegeremployeeId)    {        this.employeeId=employeeId;    }     publicStringgetName(){returnname;}     publicvoidsetName(Stringname){this.name=name;}     publicStringgetCompany(){returncompany;}     publicvoidsetCompany(Stringcompany)    {        this.company=company;    }     publicStringgetEmailId(){returnemailId;}     publicvoidsetEmailId(StringemailId)    {        this.emailId=emailId;    }     @OverridepublicStringtoString()    {        return"Employee["            +"employeeId="+employeeId+",name="+name            +","            +"company="+company+",emailId="+emailId            +"]";    }}2.WithLombok:Ajavamodelclasswithfourprivatefieldsandtheirgetters,setters,no-argsconstructor,parameterizedconstruct,andtoStringmethodusingLombokannotations.  Javaimportlombok.AllArgsConstructor;importlombok.Getter;importlombok.NoArgsConstructor;importlombok.Setter;importlombok.ToString; @NoArgsConstructor@AllArgsConstructor@ToStringpublicclassEmployee{    private@Getter@SetterIntegeremployeeId;    private@Getter@SetterStringname;    private@Getter@SetterStringcompany;    private@Getter@SetterStringemailId;}Thedifferenceisclearlyvisibleinthecodes.Theoriginalsourcecodecontainsaround60linesofcodewhichhasbeenreducedbyLomboktoaround20linesofcodeonly.Itnotonlyreducesthelinesofcodebutalsoincreasesthereadabilityandmaintainabilityofsourcecode. HowtoconfigureprojectLomboktoeclipse?  1.DownloadtheLombokjarfilefromthisofficiallink.2.Doubleclickonthedownloadedjarfiletoexecuteit.AGUIwillappeartospecifytheIDEinwhichyouwanttopluginit.   3.ClickonspecifyalocationandselecttheIDE.4.Clickoninstalltocompletetheinstallationandthenquittheinstaller.5.Toverifythecorrectinstallation,gototheEclipseIDE,selecthelp,andthenabouttheeclipse.YouwillseeprojectLombokinstalledthere. Lombokannotations: Lombokprovidesasetofannotationstomakeourcodinglifeeasier.LetuslookatthefewmostfrequentlyusedannotationsofLombok.  1.@Getterand@Setter:Theseannotationsprovidethegetterandsettermethodsforafield.Theseannotationscanbeusedatboththelevels,fieldaswellasclass.@GetterannotationgeneratesagettermethodwithaccesstypeaspublicwhichsimplyreturnsthefieldandwithnamegetName()ifthefieldnameis“Name”.@Setterannotationgeneratesasettermethodwithaccesstypeaspublicwhichreturnsvoidandtakesasingleparametertoassignthevaluetothefield.ThedefaultsetterwillhavethenamesetName()ifthefieldnameis“Name”.  Javaimportlombok.Getter;importlombok.Setter; publicclassEmployee{    private@Getter@SetterIntegeremployeeId;    private@Getter@SetterStringname;    private@Getter@SetterStringcompany;    private@Getter@SetterStringemailId;}2.@NoArgsConstructor:Thisannotationisusedtogenerateaconstructorwithnoarguments.Ithasanemptybodyanddoesnothing.Itisgenerallyusedincombinationwithsomeotherparameterizedconstructorinuse.Itisrequiredwhenyouwanttogenerateanobjectoftheclassbypassingnoargumentsintheconstructor.  Javaimportlombok.NoArgsConstructor; @NoArgsConstructorpublicclassEmployee{    privateIntegeremployeeId;    privateStringname;    privateStringcompany;    privateStringemailId;}3.@AllArgsConstructor:Thisannotationisusedtogenerateaparameterizedconstructorwhichacceptsasingleparameterforeachfieldandinitializesthemusingit.Itisrequiredwhenyouwanttogenerateanobjectoftheclassbypassingtheinitialvaluesofthefieldsintheconstructor.  Javaimportlombok.AllArgsConstructor; @AllArgsConstructorpublicclassEmployee{    privateIntegeremployeeId;    privateStringname;    privateStringcompany;    privateStringemailId;}4.@ToString:ThisannotationisusedtooverridethetoString()methodandgenerateadefaultimplementationforit.Thedefaultimplementationprintstheclassnameandthefieldsinorder,separatedbycommas.Youcanalsoskipsomefieldsthatyoudon’[email protected].  Javaimportlombok.ToString; @ToStringpublicclassEmployee{    privateIntegeremployeeId;    privateStringname;    privateStringcompany;    privateStringemailId;}5.@EqualsAndHashCode:Thisannotationisusedtooverridetheequals()andhashCode()methodsandprovidesadefaultimplementationforthu.Thedefaultimplementationusesallthenon-staticfields,andwecanmodifyitandcanexcludesomefieldsusingtheannotation@EqualsAndHashCode.Exclude.  Javaimportlombok.EqualsAndHashCode; @EqualsAndHashCodepublicclassEmployee{    privateIntegeremployeeId;    privateStringname;    privateStringcompany;    privateStringemailId;}6.@Data:Thisannotationisashortcutannotationandbundles@ToString,@Getter,@Setter,@EqualsAndHashCodeand@RequiredArgsConstructorannotationsintoasingleannotation.Thisannotationprovidesallthenormallyusedboilerplatecodeinthemodelclassesofjavalikegettersforallthefields,setterforallthenon-finalfields,adefaultimplementationfortoString(),equals()andhashCode()usingallthefieldsoftheclassandaconstructorthatinitializesallthefieldsoftheclass.  Javaimportlombok.Data; @DatapublicclassEmployee{    privateIntegeremployeeId;    privateStringname;    privateStringcompany;    privateStringemailId;}MyPersonalNotes arrow_drop_upSave LikePreviousSimplifiedInternationalDataEncryptionAlgorithm(IDEA)Next DifferencebetweenIncrementandDecrementOperatorsRecommendedArticlesPage:13,Nov1520,Nov1820,Sep1830,Jul1708,Aug1723,Jun1825,Aug2010,Dec1725,Jun1806,Jul1818,Jul1801,Jul2118,Sep2101,Jul2117,Aug2110,Aug2117,Dec1507,Nov1507,Nov1508,Nov1509,Nov1510,Nov1513,Nov1523,Nov15ArticleContributedBy:raman_257@raman_257VotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:chbs17csAnshul_AggarwalArticleTags:java-advancedArticlesJavaProgramsProjectReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinArticlesRegularexpressionsinCTimeComplexityandSpaceComplexityDocker-COPYInstructionTimecomplexitiesofdifferentdatastructuresSQL|DROP,TRUNCATEMostvisitedinJavaProgramsConvertaStringtoCharacterarrayinJavaInitializingaListinJavaJavaProgrammingExamplesConvertDoubletoIntegerinJavaImplementingaLinkedListinJavausingClass× Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?