JBuilder 2005 提供強大的重構向導,可將舊版 Java 代碼一鍵遷移至 JDK 5.0 新語法(自動裝箱/拆箱、泛型、增強 for 循環、靜態導入、枚舉、可變參數等)。本文實戰演示核心重構操作與代碼變化對比。
public static void autoBoxingPreliminary(Integer intObject) {
System.out.println(intObject);
}
public static void autoBoxingRefactoring() {
autoBoxingPreliminary(new Integer(8)); // 手動裝箱
}
public static void autoBoxingRefactoring() {
autoBoxingPreliminary(8); // 自動裝箱:int → Integer
}
效果:消除 new Integer()、.intValue() 樣板代碼,編譯器自動插入裝箱/拆箱字節碼指令。
public static void genericsArrayList() {
List list = new ArrayList(); // 原始類型
list.add(0, new Integer(23));
int total = ((Integer) list.get(0)).intValue(); // 強制轉型 + 拆箱
System.out.println(total);
}
對話框中 Type Argument 自動推斷為 Integer,確定即可。
public static void genericsArrayList() {
List list = new ArrayList(); // 參數化類型
list.add(0, new Integer(23));
int total = list.get(0).intValue(); // 無需強轉,直接拆箱
System.out.println(total);
}
進階:配合自動裝箱重構,list.add(0, 23) 直接傳 int。
for (Iterator it = list.iterator(); it.hasNext(); ) {
String s = (String) it.next();
System.out.println(s);
}
for (String s : list) {
System.out.println(s);
}
System.out.println(Math.PI);
Thread.sleep(1000);
import static java.lang.System.out;
import static java.lang.Math.PI;
import static java.lang.Thread.sleep;
out.println(PI);
sleep(1000);
public void printAll(String[] messages) { ... }
printAll(new String[]{"A", "B", "C"});
public void printAll(String... messages) { ... }
printAll("A", "B", "C");
public static final int RED = 1, GREEN = 2, BLUE = 3;
public enum Color { RED, GREEN, BLUE }
assertEquals、PI),避免命名空間污染善用 IDE 重構,讓遷移 JDK 5.0 從「大工程」變為「例行公事」。