Eclipse中setter/getter方法自動添加屬性註釋

這篇文章以前在公司內網發的,到現在也一直有用,發上來分享給有用的人

 

一、修改eclipse的setter/getter生成的源碼

  1. 用git下載源碼git://git.eclipse.org/gitroot/jdt/eclipse.jdt.ui.git

  2. 將版本歷史切換到eclipse/plugins/org.eclipse.jdt.ui_*.jar包打包之前的最新版本

  3. 將其中的四個項目(org.eclipse.jdt.core.manipulation、org.eclipse.jdt.ui、org.eclipse.ltk.core.refactoring、org.eclipse.ltk.ui.refactoring)導入workspace

  4. 切換到項目org.eclipse.jdt.ui,配置Build Path,切換到Libraries,點擊Add External JARs,找到eclipse/plugins目錄,找到其中的org.eclipse.jdt.core_*.jar和org.eclipse.jface.text_*.jar添加到項目依賴包中。(此時項目可能依然有類報錯,沒關係,只要我們要改的類不報錯就行了)

  5. 然後打開core extension源碼目錄,找到其中的org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil類

  6. 搜索關鍵字"CodeGeneration.getSetterComment"和"CodeGeneration.getGetterComment",分別在這兩個查找到的內容下面一行中加入以下代碼:

    ISourceRange sr= field.getJavadocRange();
    if (null != sr) {
    	String filedComment= field.getSource();
    	filedComment= filedComment.substring(0, sr.getLength()).replaceAll("[\n,\r,*,/,\t]", "").trim(); //$NON-NLS-1$ //$NON-NLS-2$
    	comment= comment.replace("#{bare_field_comment}", filedComment); //$NON-NLS-1$
    } 
  7. 修改完GetterSetterUtil後保存,之後到項目的bin目錄下找到該類編譯後的class文件複製出來。

二、將修改的好的GetterSetterUtil導入Eclipse

  1. 導入前關閉eclipse
  2. 用winrar或類似解壓縮軟件打開eclipse/plugins/org.eclipse.jdt.ui_*.jar,找到org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil類,將複製的class拖入替換
  3. 啓動eclipse

三、修改代碼模板

  1. 打開Window > Preferences > Java > Code Style > Code Templates
  2. 展開Comments > 設置Getters的Pattern
    /**
     * 獲取 #{bare_field_comment}
     * @return ${bare_field_name}
     */
  3. 設置Setters的Pattern
    /**
     * 設置 #{bare_field_comment}
     * @param ${param} #{bare_field_comment}
     */
  4. 保存Apply

四、使用功能

  1. 定義屬性
    private String uuserid
  2. 在屬性上方輸入代碼"/**",然後回車,添加相關注釋如,用戶ID
    /**
     * 用戶ID
     */
    private String uuserid
  3. 使用快捷鍵 shift+alt+s 打開源碼控制面板,選擇Generate Getters and Setters...,然後勾選要生成的get/set方法,Insertion point選擇Last member(意爲將方法生成在類的末尾),勾選Generate method comments,點擊OK 即可在類的最後生成代碼如下:
    /**
     * 獲取 用戶ID
     * @return uuserid
     */
    public String getUuserid() {
        return uuserid;
    }
        
    /**
     * 設置 用戶ID
     * @param uuserid 用戶ID
     */
    public void setUuserid(String uuserid) {
        this.uuserid = uuserid;
    }
     
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章