在 Eclipse Galileo 中更快地编写 Java 代码使用新的 toString() 生成器
http://www.ibm.com/developerworks/cn/opensource/os-eclipse-codegen/
這個代碼生成技巧使用 Eclipse Galileo 中的新特性。但是,您也可以使用在這里介紹的、舊版本 Eclipse(如 Ganymede)中的某些技巧(如生成 getters 和 setters)。
代碼生成概述
在日常使用的 Eclipse 特性中,Source 菜單中用于代碼生成的項目是用得最多的。我花了很多時間來學習如何有效使用它們,但是掌握了這些特性后,我就能夠很快地構建 Java 類了。
例如,創建新類時,我不再花時間編寫 setter 和 getter(訪問器),也不用編寫大部分的構造器。相反,我創建類并快速在類中輸入私有變量,如清單 1 所示。
清單 1. 私有變量
| public class Automobile {private String make;private String model;private String year;} |
然后,單擊 Source > Generate Getters and Setters,選擇剛才輸入的、想用公共訪問器公開的私有變量。要使用構造器初始化部分變量,單擊 Source > Generate Constructor using Fields 以快速創建構造器。只需點擊幾下鼠標,一個類就差不多創建完成了,具體情況取決于要用該類實現什么功能(見清單 2)。理想的情況是,新創建的代碼應該遵守此前在 Eclipse 首選項中設置的代碼格式規則。
清單 2. 自動創建構造器和訪問器
| public class Automobile {private String make;private String model;private String year;public String getMake() {return make;}public Automobile(String make, String model, String year) {super();this.make = make;this.model = model;this.year = year;}public void setMake(String make) {this.make = make;}public String getModel() {return model;}public void setModel(String model) {this.model = model;}public String getYear() {return year;}public void setYear(String year) {this.year = year;}} |
除了可以用 Source 菜單項生成代碼外,還可以通過使用 Ctrl+Space 快捷鍵編寫許多公共代碼塊來生成大量代碼。要弄清生成特定的代碼塊需要使用的名稱,查看 Preferences 窗口。例如,輸入 lazy,然后按下 Ctrl+Space,這將生成用于延遲加載的 Java 代碼。
回頁首
代碼生成設置
新方法的代碼生成設置在 Java > Code Style > Code Templates 下面的 Preferences 窗口中修改。
圖 1. Java > Code Style > Code Templates 首選項
總結您的最佳實踐
作為幾個項目的技術主管,我已經確認了一些希望在我們的項目中采用的最佳實踐。我將它們放在 Java 代碼模板中,供團隊成員導入。
Preferences 窗口中的 Java > Editor > Code Templates 設置根據名稱列示模板(見圖 2)。仔細檢查 Eclipse 帶有的模板。您可以添加自己的模板,也可以導入模板。
圖 2. Java > Editor > Code Templates 首選項
回頁首
使用 toString() 生成功能
Eclipse Galileo 中的一個新特性是能夠生成 toString() 方法。默認情況下,toString() 方法輸出一個類的表示,這也許不能真正顯示您想要查看的屬性。檢查清單 3 中的 main 方法。
清單 3. 使用 toString() 輸出 Automobile
| public class Main {public static void main(String[] args) {Automobile auto = new Automobile("Toyota", "Corolla", "1993");System.out.println(auto.toString());} } |
這個應用程序的輸出如清單 4 所示。
清單 4. Main 方法的輸出
| Automobile@77df38fd |
在 Galileo 之前,我必須手工編寫 toString() 方法。盡管編寫這個小類并不是太費力,但如果一個類擁有許多字段,編寫工作就會花費一些時間。我可能想做很多事情(比如檢查一些空值),而不僅僅是串聯一些值。也許我想使用一個 StringBuilder 來獲得更好的性能。但是對于 Galileo,我可以使用 Source > Generate toString() 來完成上述所有任務,如圖 3 所示。
圖 3. 生成 toString()
單擊 Finish 之后,新的 toString() 方法如清單 5 所示。
清單 5. 自動生成的 toString() 方法
| ...@Overridepublic String toString() {return "Automobile [" + (make != null ? "make=" + make + ", " : "")+ (model != null ? "model=" + model + ", " : "")+ (year != null ? "year=" + year : "") + "]";} ... |
現在,main 方法運行時,輸出如清單 6 所示。
清單 6. 自動生成的 toString() 方法的輸出
| Automobile [make=Toyota, model=Corolla, year=1993] |
回頁首
格式化字符串
即使清單 6 中顯示的輸出比清單 4 中的原始輸出更具描述性,但調整一下輸出格式使其更具可讀性可能會更好,比如 “1993 Toyota Corolla (Automobile)”。自定義模板允許您調整 toString() 方法生成的輸出。
刪除 toString() 方法并再次單擊 Source > Generate toString()。這次:
圖 4. 添加一個新格式
選中新模式,在 Generate toString() 上單擊 OK。新代碼如清單 7 所示。
清單 7. 更新后的 toString() 方法
| ...@Overridepublic String toString() {return (make != null ? make + " " : "")+ (model != null ? model + " " : "")+ (year != null ? year : "") + " (Automobile)";} ... |
現在,運行 main 方法,Automobile 對象的 toString() 輸出如清單 8 所示。
清單 8. Automobile 對象的 toString() 方法的輸出
| Toyota Corolla 1993 (Automobile) |
回頁首
處理數組
您還能使用 toString() 生成器處理數組。清單 9 展示了一個稱為 options 的新的字符串數組。
清單 9. options 字符串數組
| Automobile auto = new Automobile("Toyota", "Corolla", "1993");String[] options = new String[] {"Automatic Transmission","Power Brakes","Power Windows"};// new generated method after adding private String[] options;auto.setOptions(options);System.out.println(auto.toString());// prints this:// Toyota Corolla [Ljava.lang.String;@defb836 1993 (Automobile) |
通常,原生 toString() 方法輸出的數組表示就像對象的原始表示一樣,并不真正顯示內容。但是,選項 List contents of arrays instead of using native toString 改變了這種情況。選中該選項,重新生成 toString() 方法,新的輸出如清單 10 所示。
清單 10. 重新生成的 toString() 方法的輸出
| Toyota Corolla [Automatic Transmission, Power Brakes, Power Windows] 1993 (Automobile) |
回頁首
限制輸出
如果某些數組非常大,可以通過選中 Limit number of items in arrays/collections/maps 并設置限制來約束輸出的內容(見圖 5)。這樣做可以阻止 toString() 方法輸出過多內容。
圖 5. 輸出數組內容并施加限制
清單 11 顯示了將限制設置為 2 的情況。
清單 11. 將數組內容限制為 2
| Toyota Corolla [Automatic Transmission, Power Brakes] 1993 (Automobile) |
回頁首
使用 hashCode() 和 equals()
有時,您需要創建一些規則,根據實際的字段值將您的對象變為相等的對象。這時,使用 Eclipse Galileo hashCode() 和 equals() 生成功能真的很方便。這不同于 equals() 的默認行為,因為即使默認擁有相同值的對象也不會是相等的。看看清單 12 中的代碼。
清單 12. equals() 方法的默認行為
| public class Main {public static void main(String[] args) {Automobile auto = new Automobile("Toyota", "Corolla", "1993");String[] options = new String[] {"Automatic Transmission","Power Brakes","Power Windows"};auto.setOptions(options);Automobile auto2 = new Automobile("Toyota", "Corolla", "1993");String[] options2 = new String[] {"Automatic Transmission","Power Brakes","Power Windows"};auto2.setOptions(options2);System.out.println("Autos 1 and 2 are equal(): " + auto.equals(auto2));} } |
即使所有屬性值設置為相同的值,代碼執行時也會輸出 Auto 1 and 2 are equal(): false。
要改變這種行為,單擊 Source > Generate hashCode() and equals() 以生成 equals() 方法的一個新版本,新的方法將比較所有字段,如下所示。
清單 13. 用新的 equals() 方法比較所有字段
| @Overridepublic int hashCode() {// snipped...}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Automobile other = (Automobile) obj;if (make == null) {if (other.make != null)return false;} else if (!make.equals(other.make))return false;if (model == null) {if (other.model != null)return false;} else if (!model.equals(other.model))return false;if (!Arrays.equals(options, other.options))return false;if (year == null) {if (other.year != null)return false;} else if (!year.equals(other.year))return false;return true;} |
現在,執行這段代碼時,這兩個對象使用覆蓋后的 equals() 方法進行比較,所以二者是相同的。
Eclipse Galileo 中的另一個新特性是為 if 語句生成代碼塊的能力。如果您還沒有將 Source > Clean Up 配置為將單行 if 語句轉換為代碼塊,這個新特性很有用。避免使用單行 if 語句通常被認為是最佳實踐,因此許多人愿意確保他們的代碼遵守這個最佳實踐。
回頁首
結束語
Galileo 中生成 toString() 方法的新特性增強了 Eclipse 生成大量 Java 代碼的能力。通過實踐,您可以明確哪些代碼必須手工輸入,哪些代碼可以自動生成,從而減少您的工作量。
?
總結
以上是生活随笔為你收集整理的在 Eclipse Galileo 中更快地编写 Java 代码使用新的 toString() 生成器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: show in Breadcrumb
- 下一篇: telnet命令详解