3.9. Creating Getter/Setter Methods

Problem

You need to create getter/setter methods for a field (for example, when creating properties in a JavaBean©), and you are looking for a shortcut.

Solution

Select Source Generate Getter and Setter.

Discussion

Say your code uses a field named text to store the text it displays:

public class DisplayApp {

    static String text = "No problem.";
    
    public static void main(String[] args)
    {
        System.out.println(text);
    }
}

Instead of storing that data in a simple field, you can create getter and setter methods for that data, making access to the data from outside the class more secure. To automatically create getter and setter methods, select Source Generate Getter and Setter, opening the dialog shown in Figure 3-12. Select the field for which you want a getter and setter, as well as the methods to create, and click OK.

Creating getter/setter methods

Figure 3-12. Creating getter/setter methods

This creates the new getter and setter methods shown here:

public class DisplayApp {

    static String text = "No problem.";
    
    public static void main(String[] args)
    {
        System.out.println(getText( ));
    }
    /**
     * @return
     */
    public static String getText( ) {
               return text;
               }

    /**
     * @param string
     */
    public static void setText(String string) {
               text = string;
               }

}

Get Eclipse Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.