一直對一些問題沒有去深的研究,有人說Intellij好,有人說MyEclipse好,有人說Eclipse好,其實蘿蔔青菜各有所愛,只是看大家使用的習慣或者說公司用什麼,你不能左右的時候,請去適合周圍的環境,當我們說建立一個類的時候,最後去重寫其toString方法,但是我們是否考慮過生成自己喜歡的風格呢? 下面我就來介紹一下使用Eclipse定製生成toString模版
Eclipse官方文件
這裡我借鑑了 https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fref-dialog-tostring.htm 文件說明,稍後再來回顧
定製toString模版圖解
-
1.點選toString方法
-
2.點選編輯按鈕
-
3.點選New按鈕設計新的規則
-
4.定製生成Json格式的規則策略
{"className":"{object.getClassName}","{member.name()}":"{member.value}","{otherMembers}"} 複製程式碼
點選OK完成,之後需要在toString的頁面設定
-
5.最後一步設定
-
6.生成效果如下
@Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("{\""); if (this.role_id != null) { builder.append("role_id\":\""); builder.append(this.role_id); builder.append("\",\""); } if (this.role_name != null) { builder.append("role_name\":\""); builder.append(this.role_name); builder.append("\",\""); } if (this.role_key != null) { builder.append("role_key\":\""); builder.append(this.role_key); builder.append("\",\""); } if (this.status != null) { builder.append("status\":\""); builder.append(this.status); } builder.append("\"}"); return builder.toString(); } 複製程式碼
模版屬性簡單說明
${object.className} |
inserts the class name as a simple String |
---|---|
${object.getClassName} |
inserts a call to this.getClass.getName() |
${object.superToString} |
inserts a call to super.toString() |
${object.hashCode} |
inserts a call to this.hashCode() |
${object.identityHashCode} |
inserts a call to System.identityHashCode(this) |
${member.name} |
inserts the first member's name |
${member.name()} |
inserts the first member's name followed by parenthesis in case of methods |
${member.value} |
inserts the first member's value |
${otherMembers} |
inserts the remaining members. For each member, the template fragment between the first and the last ${member.*} variable is evaluated and appended to the result. The characters between the last ${member.*} and ${otherMembers} define the separator that is inserted between members (${otherMembers} must stand after the last ${member.*} variable). |