NetBeans Quick Tip #2 - Generating Getters and Setters

Guest Author

Somebody has asked recently on of the mailling lists how to generate getters and setters in NetBeans. I've mentioned that some people even thought NetBeans doesn't have that functionality! So yes, it exists, only it's disguised as "Encapsulate Fields".

You can invoke the action either from the context menu in editor or from the main menu. In both cases use Refactor | Encapsulate Fields. The following dialog pops up and it lets you create getters and setters for all fields in the class:

The good news is that generating getters and setters will be available through the code completion in next release, which will make this feature much more discoverable:

Join the discussion

Comments ( 7 )
  • Valère Déjardin Thursday, May 26, 2005
    In the older versions of NB (at least 3.6) the "create getter and setter" had a functionnality that is now gone: generate javadoc for these getter and setter. Is there a tip that I missed with the "Encapsulate fields" refactoring tool?
  • Jamie Lawrence Thursday, May 26, 2005
    I hope the "Create g/setter" in the code completion will only be available if those g/setters don't already exist.
  • Roman Strobl Thursday, May 26, 2005
    To Valere: I don't think there's such an option. You can add the javadoc through autocomment tool. But I understand you would like to have this automated. There's a filed enhancement for this in Issuezilla, feel free to vote for it.

    To Jamie: yes and it works already this way in the experimental version from which I made the screenshot. Only non-existing getters/setters appear as options.
  • Valère Déjardin Thursday, May 26, 2005
    Thanks, I voted for it.
  • Iwan Eising Thursday, September 1, 2005
    It would also be nice if you could just annotate the field with @property and the IDE would create the getters for me.
  • Iwan Eising Thursday, September 1, 2005
    Hi Roumen,

    Thanks for the great tips. Here's a suggestion I haven't seen anywhere yet, it's regarding getters and setters: How about 'boxing' the Object-versions of the primitive types in getters and setters?

    I quite often need to use these object primitves, and most commonly Boolean, because I need to work with objects rather than primitives, but it is so handy to treat them like primitives, so I create getters and setters that work with the primitives as well. For Boolean objects I create not only the getMyBoolean, but also the isMyBoolean which returns a <u>b</u>oolean.
  • Anonymous Person Thursday, October 25, 2007

    Hi Roumen,

    Any chance of generating PropertyChange support for the setters as well?

Please enter your name.Please provide a valid email address.Please enter a comment.CAPTCHA challenge response provided was incorrect. Please try again.