Recipe 3.9 Creating GetterSetter Methods

     

Recipe 3.9 Creating Getter/Setter Methods

3.9.1 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.

3.9.2 Solution

Select Source Generate Getter and Setter.

3.9.3 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.

Figure 3-12. Creating getter/setter methods
figs/ecb_0312.gif

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;   }  } 



Eclipse Cookbook
Inside XML (Inside (New Riders))
ISBN: 596007108
EAN: 2147483647
Year: 2006
Pages: 232
Authors: Steve Holzner

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net