Eclipse’s Setter/Getter Shortcut

Posted: November 7th, 2011 | Author: | Filed under: Android, Java, Tech | No Comments »

The following tip probably won’t change your world, but I thought I would share it to save people time that weren’t aware of it. Unfortunately, Java does not have Auto-Implemented Properties like C# does. If you are going to obey object-oriented principles, you will need to create a private field for each property and then create a getter method and a setter method if both are needed. This can be very tedious as the majority of time there is no additional logic needed before setting the field or getting the field. Luckily, if you are using Eclipse for Java development, you can use the built in shortcut to automatically generate your getter and setter methods. First, you will create the private fields that are needed for your class (Figure 1). After you have created your private fields, you can generate the methods by clicking on Source in the menu bar and then “Generate Getters and Setters.” A dialog (Figure 2) will appear. Here you can check what fields you want getters and setters for. If you only want one or the other, you can expand the field and choose the appropriate option for what method want. After you have done this and then clicked OK, your code will be inserted into your class (Figure 3).



Leave a Reply