這篇文章以前在公司內網發的,到現在也一直有用,發上來分享給有用的人
一、修改eclipse的setter/getter生成的源碼
-
用git下載源碼git://git.eclipse.org/gitroot/jdt/eclipse.jdt.ui.git
-
將版本歷史切換到eclipse/plugins/org.eclipse.jdt.ui_*.jar包打包之前的最新版本
-
將其中的四個項目(org.eclipse.jdt.core.manipulation、org.eclipse.jdt.ui、org.eclipse.ltk.core.refactoring、org.eclipse.ltk.ui.refactoring)導入workspace
-
切換到項目org.eclipse.jdt.ui,配置Build Path,切換到Libraries,點擊Add External JARs,找到eclipse/plugins目錄,找到其中的org.eclipse.jdt.core_*.jar和org.eclipse.jface.text_*.jar添加到項目依賴包中。(此時項目可能依然有類報錯,沒關係,只要我們要改的類不報錯就行了)
-
然後打開core extension源碼目錄,找到其中的org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil類
-
搜索關鍵字"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$ }
- 修改完GetterSetterUtil後保存,之後到項目的bin目錄下找到該類編譯後的class文件複製出來。
二、將修改的好的GetterSetterUtil導入Eclipse
- 導入前關閉eclipse
- 用winrar或類似解壓縮軟件打開eclipse/plugins/org.eclipse.jdt.ui_*.jar,找到org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil類,將複製的class拖入替換
- 啓動eclipse
三、修改代碼模板
- 打開Window > Preferences > Java > Code Style > Code Templates
- 展開Comments > 設置Getters的Pattern
/** * 獲取 #{bare_field_comment} * @return ${bare_field_name} */
- 設置Setters的Pattern
/** * 設置 #{bare_field_comment} * @param ${param} #{bare_field_comment} */
- 保存Apply
四、使用功能
- 定義屬性
private String uuserid
- 在屬性上方輸入代碼"/**",然後回車,添加相關注釋如,用戶ID
/** * 用戶ID */ private String uuserid
- 使用快捷鍵 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; }