Eclipse: Auto generate Getters and Setters methods for properties

By Akbar

I have been using the Eclipse for Android development for few months, and I must say I’m really impressed with this editor so far. Though for a newbie, it looks very cluttered, and I had some hard time in start getting used to it, but the more I work on it, the move I’m loving it.

When working today, I needed to add a new class with a lot of properties (private variables). Having years of experience working on the Visual Studio, I had a hunch that there must be something in Eclipse to automate this tedious process too. And as I looked more carefully, there was indeed an option. In fact, there are more than one options and you may have preference to use one or other depending on you coding style.

The simplest (and the one I found exploring) is by the menu (while in the source code of the Java file):
Eclipse Main Menu -> Source -> Generate Getters and Setters

This brings up a dialog which shows all the private variables, and lets you generate the Getter and Setter methods for each. This dialog also feature a nice option to also generate the comments. While these comments are not very explanatory, but at least this provide some skeleton which you can later modify. You can see more detail about this here at Eclipse help:
http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fref-dialog-gettersetter.htm

Remember I told you there are many methods to automatically generate these getters and setters. So here are the other two methods I know off:

1) First is that once you have typed a property name (as private variable), wait for few seconds and Eclipse will shortly underline this with a yellow line. Click on that link, and it will show you an option to auto generate getter and setter method for this newly added property.

2) The second somewhat geeky method is once you have typed the private variable, and don’t want to wait for eclipse to detect and highlight that, you can still generate getter and setter by typing “set” on new line and then wait for few seconds (or press hitting Ctrl+Space key). Eclipse should show a popup dialog with option to generate setter for all your private variables. Similarly to generate the getter, type “get” and hit Ctrl+Space key.

I hope you find this handy, and this makes development in Eclipse even easier for you.

Tags: , , ,