首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> J2ME

Java 源碼級解析:java.lang.System 核心實現與 J2ME 差異

     編輯:J2ME

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 方法核心功能

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 通常不建議直接呼叫)

實務建議

  1. **除錯輸出**:使用 System.out.println() 僅限模擬器開發期,真機測試需改用 Log 類、檔案寫入或無線除錯工具
  2. **屬性查詢**:System.getProperty("microedition.platform")、"microedition.configuration"、"microedition.profiles" 等為標準屬性,廠商擴展屬性參考各廠商文檔
  3. **時間測量**:System.currentTimeMillis() 為跨平台唯一可靠計時基準
  4. **陣列複製**:大量資料搬移優先使用 System.arraycopy(),比手寫迴圈快數倍
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方法用途
currentTimeMillis()高精度時間戳 (ms)
arraycopy()高效陣列複製 (JVM 內部優化)
identityHashCode()物件身份雜湊碼 (不隨 GC 移動改變)
getProperty0()系統屬性查詢