1. 程式人生 > >玩轉Eclipse — 自動生成setter和getter方法

玩轉Eclipse — 自動生成setter和getter方法

        我們在程式開發過程中,往往要編寫這樣的類:類的部分或者全部屬性不希望讓外部世界直接訪問,而不用public欄位修飾。這樣,方法呼叫成了訪問這些屬性的唯一途徑。JavaBean就是一個很好的例子,其嚴格遵守面向物件的設計邏輯,所有屬性都是private。對於任何屬性xxx,都有public的getXxx()方法來獲取屬性和public的setXxx()方法來修改屬性。如果只有少量這樣的屬性,可以通過手動方式為它們新增setter和getter方法。但是,如果有大量這樣的屬性,手動新增會很費時。

        下面通過一個示例,來介紹如何通過Eclipse自動生成需要的setter和getter方法。示例程式碼如下:

/**
 * The Class Boy.
 */
public class Boy {
    
    /** The name. */
    private String name;
    
    /** The age. */
    private int age;
    
    /** The smart. */
    private boolean smart;
}

1.  基本設定

        在程式碼編輯器中開啟Boy.class檔案,使用快捷鍵Alt + Shift + S,再按R鍵(你Eclipse中的快捷鍵可能不同),或者右鍵選擇Source -> Generate Getters and Setters...

,操作如下圖所示:


        進入自動生成setter和getter方法的設定介面如下:


  • Select

Select All:選擇為所有的屬性新增setter和getter方法

Deselect All:取消所有已選擇的setter和getter方法

Select Getters:選擇所有屬性的getter方法

Select Setters:選擇所有屬性的setter方法

  • Insertion point

可以選擇為該檔案的“First Member”,“Last Member”,或者某個元素之後等。

  • Sort by

Fields in getter/setter pairs:每個屬性的getter和setter方法成對排序

First getters, then setters:所有的getter方法在所有的setter方法之前

  • Access modifier

可以選擇訪問許可權:public,protected,default,private

還可以選擇是否為final或者synchronized

  • Comments

可以選擇是否在自動生成setter和getter方法的同時,為它們生成註釋

       另外,在Code Template中可以設定自動生成的setter和getter方法的主體和註釋的格式。

2. setter方法的引數加字首

        一般情況下,自動生成的setter方法中的引數,會跟屬性完全相同,需要通過this來區分同名屬性和引數。示例如下:

    /**
     * @param age the age to set
     */
    public final void setAge(int age) {
        this.age = age;
    }

        在比較嚴的程式碼格式檢查中,這種情況會提示‘xxx’ hides a field的問題。為了避免這種checkstyle的問題,通過在該專案的.settings目錄下的org.eclipse.jdt.core.prefs檔案,在其末尾新增org.eclipse.jdt.core.codeComplete.argumentPrefixes=new,就可以在自動建立的所有setter方法的引數前面加上new字首。這種配置,需要重新啟動Eclipse才能生效。這種方法的具體操作和分析,可以參考《玩轉Eclipse — 專案的.settings目錄解密》

        進行以上配置之後,自動生成的setter和getter方法後的完成的程式碼如下:

/**
 * The Class Boy.
 */
public class Boy {
    
    /** The name. */
    private String name;
    
    /** The age. */
    private int age;
    
    /** The smart. */
    private boolean smart;

    /**
     * @return the name
     */
    public final String getName() {
        return name;
    }

    /**
     * @param newName the name to set
     */
    public final void setName(String newName) {
        name = newName;
    }

    /**
     * @return the age
     */
    public final int getAge() {
        return age;
    }

    /**
     * @param newAge the age to set
     */
    public final void setAge(int newAge) {
        age = newAge;
    }

    /**
     * @return the smart
     */
    public final boolean isSmart() {
        return smart;
    }

    /**
     * @param newSmart the smart to set
     */
    public final void setSmart(boolean newSmart) {
        smart = newSmart;
    }
}
        說明:

                1)setter方法的引數會自動大寫屬性的首字母,並加上字首。

                2)setter方法的引數在屬性前面加了字首之後,就沒有必要再用this區分屬性和引數。

                3)對於boolean型別的屬性,getter不再是get開頭,而是以is開頭。