System 類別核心原始碼 (J2SE 參考實作)
public final class System {
private System() {}
public final static PrintStream out = getConsoleOutput();
private static PrintStream getConsoleOutput() {
return new PrintStream(new SystemOutputStream());
}
public final static PrintStream err = out;
public static native long currentTimeMillis();
public static native void arraycopy(Object src, int srcPos,
Object dst, int dstPos, int length);
public static native int identityHashCode(Object x);
public static String getProperty(String key) {
if (key == null) throw new NullPointerException("key can't be null");
if (key.equals("")) throw new IllegalArgumentException("key can't be empty");
return getProperty0(key);
}
private native static String getProperty0(String key);
public static void exit(int status) {
Runtime.getRuntime().exit(status);
}
public static void gc() {
Runtime.getRuntime().gc();
}
}
SystemOutputStream 實現
public class SystemOutputStream extends OutputStream {
synchronized public void write(int c) throws IOException {
putchar((char) c);
}
private static native void putchar(char c);
}
關鍵觀察與 J2ME 差異
1. 靜態工具類設計
private System() 防止實例化
- 所有方法皆為
static,提供系統級便利功能
2. 標準輸出實現鏈
System.out → PrintStream → SystemOutputStream → native putchar() → C putchar()
- 底層最終調用 C 標準庫
putchar
System.err 默認指向同一輸出流
3. Native 方法核心功能
| 方法 | 用途 |
currentTimeMillis() | 高精度時間戳 (ms) |
arraycopy() | 高效陣列複製 (JVM 內部優化) |
identityHashCode() | 物件身份雜湊碼 (不隨 GC 移動改變) |
getProperty0() | 系統屬性查詢 |
4. 委派給 Runtime
exit() → Runtime.exit()
gc() → Runtime.gc()
J2ME / 手機平台關鍵差異
手機沒有控制台 (Console):不像 Windows DOS 或 Linux Bash,手機裝置無標準輸出裝置。
System.out.println() 在真機上 不會顯示任何內容
- 僅在 **模擬器/遠端除錯** 時有控制台輸出
- 無標準輸入流 (
System.in 不存在或無效)
- J2ME
System 類精簡版,僅保留:currentTimeMillis()、arraycopy()、getProperty()、gc()、exit() (MIDlet 生命週期受 AMS 管理,exit 通常不建議直接呼叫)
實務建議
- **除錯輸出**:使用
System.out.println() 僅限模擬器開發期,真機測試需改用 Log 類、檔案寫入或無線除錯工具
- **屬性查詢**:
System.getProperty("microedition.platform")、"microedition.configuration"、"microedition.profiles" 等為標準屬性,廠商擴展屬性參考各廠商文檔
- **時間測量**:
System.currentTimeMillis() 為跨平台唯一可靠計時基準
- **陣列複製**:大量資料搬移優先使用
System.arraycopy(),比手寫迴圈快數倍
- 上一篇文章: Ant 實戰教程:從入門到多模組專案建構最佳實踐
- 下一篇文章: J2ME 發送簡訊 (SMS) 完整實作指南:WMA API 詳解與程式碼範例
Copyright ©
程式碼之家 All Rights Reserved