java.lang.System

來源:互聯網
上載者:User

package java.lang;

import java.io.*;
import java.util.Properties;
import java.util.PropertyPermission;
import java.util.StringTokenizer;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.AllPermission;
import sun.net.InetAddressCachePolicy;
import sun.reflect.Reflection;
import sun.security.util.SecurityConstants;

/**
 *
 * System類中提供了標準輸入,標準輸出,標準錯誤輸出,提供了擷取系統屬性的能力
 * 提供了裝載檔案和連結庫的能力,還提供了快速拷貝數組的本地方法,他的所有方法都為靜態
 *
 * comment by liqiang
 *
 * @author  Arthur van Hoff
 *
 */
public final class System {
    private static native void registerNatives();
    static {
        registerNatives();
    }

    //私人的建構函式,此類沒有執行個體
    private System() {
    }

    //用null做初始化,如果currentTimeMillis不大於0拋出異常
    //表示標準輸入
    public final static InputStream in = nullInputStream();

    //用null做初始化,如果currentTimeMillis不大於0拋出異常
    //表示標準輸出
    public final static PrintStream out = nullPrintStream();

    //用null做初始化,如果currentTimeMillis不大於0拋出異常
    //表示標準錯誤輸出
    public final static PrintStream err = nullPrintStream();

    //安全管理器
    private static SecurityManager security = null;

    /**
     *
     * 重設標準輸入
     *
     */
    public static void setIn(InputStream in) {
    //安全檢查
 checkIO();
 
 //重設標準輸入的本地方法
 setIn0(in);
    }

    /**
     *
     * 重設標準輸出
     *
     */
    public static void setOut(PrintStream out) {
    //安全檢查
 checkIO();
 
 //重設標準輸出的本地方法
 setOut0(out);
    }

    /**
     *
     * 重設標準輸出
     *
     */
    public static void setErr(PrintStream err) {
    //安全檢查
 checkIO();
 
 //重設標準輸出的本地方法
 setErr0(err);
    }

    private static void checkIO() {
     //安全檢查
        if (security != null)
     security.checkPermission(new RuntimePermission("setIO"));
    }

    //重設標準輸入的本地方法
    private static native void setIn0(InputStream in);
    //重設標準輸出的本地方法
    private static native void setOut0(PrintStream out);
    //重設標準錯誤輸出的本地方法
    private static native void setErr0(PrintStream err);

    /**
     *
     * 設定安全管理器
     *
     */
    public static
    void setSecurityManager(final SecurityManager s) {
        try {
         //是否可以處理"java.lang"包
            s.checkPackageAccess("java.lang");
        } catch (Exception e) {
            //空操作
        }
       
        //設定安全管理器
        setSecurityManager0(s);
    }

    private static synchronized
    void setSecurityManager0(final SecurityManager s) {
 if (security != null) {
  //詢問當前的安全管理器,是否有改變安全管理器的能力
      security.checkPermission(new RuntimePermission
         ("setSecurityManager"));
 }

 if ((s != null) && (s.getClass().getClassLoader() != null)) {
     AccessController.doPrivileged(new PrivilegedAction() {
  public Object run() {
      s.getClass().getProtectionDomain().implies
   (SecurityConstants.ALL_PERMISSION);
      return null;
  }
     });
 }

 security = s;
 InetAddressCachePolicy.setIfNotSet(InetAddressCachePolicy.FOREVER);
    }

    /**
     *
     * 獲得安全管理器
     *
     */
    public static SecurityManager getSecurityManager() {
 return security;
    }

    /**
     *
     * 從January 1, 1970 UTC開始到現在時刻的毫秒數
     *
     */
    public static native long currentTimeMillis();

    /**
     *
     * 將源數組種的元素拷貝到目標數組中
     *
     * @param      src      源數組
     * @param      srcPos   源數組拷貝的起始位置
     * @param      dest     目標數組
     * @param      destPos  目標數組的起始位置
     * @param      length   拷貝的個數
     *
     */
    public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

    /**
     *
     * 返回對象x的hashCode值,無論x對應的實際類是否重寫了hashCode方法
     * 都返回原始的Object的hashCode方法的傳回值,如果對象為null則返回0
     *
     */
    public static native int identityHashCode(Object x);

    /**
     *
     * 系統屬性,下列對象必須被設定
     *
     * 下列屬性應保證被設定
     * java.version: Java的版本號碼 例如: 1.4.2_05
     * java.vendor: Java的賣主 例如: Sun Microsystems Inc.
     * java.vendor.url: Java賣主的URL 例如: http://java.sun.com/
     * java.home: Java運行環境的位置 例如:C:/j2sdk1.4.2_05/jre
     * java.class.version: Java Class檔案的版本 例如: 48.0
     * java.class.path: 系統設定的ClassPath環境變數
     * os.name: 作業系統名 例如: Windows 2000
     * os.arch: 作業系統架構 例如: x86
     * os.version: 作業系統版本 例如: 5.0
     * file.separator: 檔案分隔字元 例如: /
     * path.separator: 路徑分隔字元 例如: ;
     * line.separator: 分行符號 例如: "/n"
     * user.name: 使用者名稱 例如: Administrator
     * user.home: 使用者的home路徑 例如: C:/Documents and Settings/Administrator
     * user.dir: 當前的工作路徑 例如: D:/eclipse/workspace/test
     */
    private static Properties props;
   
    //使用一個Properties初始化系統變數
    private static native Properties initProperties(Properties props);

    /**
     *
     * 擷取系統的全部屬性
     *
     */
    public static Properties getProperties() {
    //安全檢查
 if (security != null) {
     security.checkPropertiesAccess();
 }
 
 return props;
    }

    /**
     *
     * 設定系統屬性
     *
     */
    public static void setProperties(Properties props) {
    //安全檢查
 if (security != null) {
     security.checkPropertiesAccess();
 }
 
        if (props == null) {
         //如果props為空白設定通過空的的Properties初始化它
            props = new Properties();
            initProperties(props);
        }
       
       
 System.props = props;
    }

    /**
     *
     * 通過key獲得對應的屬性
     *
     */
    public static String getProperty(String key) {
    //key為null或Null 字元串拋出異常 
 if (key == null) {
     throw new NullPointerException("key can't be null");
 }
 if (key.equals("")) {
     throw new IllegalArgumentException("key can't be empty");
 }
 
 //安全檢查
 if (security != null) {
     security.checkPropertyAccess(key);
 }
 return props.getProperty(key);
    }

    /**
     *
     * 通過key獲得屬性值
     *
     * @param      key   屬性的索引值
     * @param      def   屬性的預設值
     *
     */
    public static String getProperty(String key, String def) {
 if (key == null) {
     throw new NullPointerException("key can't be null");
 }
 if (key.equals("")) {
     throw new IllegalArgumentException("key can't be empty");
 }
 
 if (security != null) {
     security.checkPropertyAccess(key);
 }
 
 return props.getProperty(key, def);
    }

    /**
     *
     * 設定指定屬性的值
     *
     */
    public static String setProperty(String key, String value) {
 if (key == null) {
     throw new NullPointerException("key can't be null");
 }
 if (key.equals("")) {
     throw new IllegalArgumentException("key can't be empty");
 }
 if (security != null)
     security.checkPermission(new PropertyPermission(key,
  SecurityConstants.PROPERTY_WRITE_ACTION));
 return (String) props.setProperty(key, value);
    }

    /**
     *
     * @deprecated
     *
     */
    public static String getenv(String name) {
 throw new Error("getenv no longer supported, use properties and -D instead: " + name);
    }

    /**
     *
     * 退出虛擬機器
     *
     * @param status 狀態代碼,約定0表示
     * @throws  SecurityException
     *
     */
    public static void exit(int status) {
    //實際調用的是Runtime的相應方法
 Runtime.getRuntime().exit(status);
    }

    /**
     *
     * 手動進行記憶體回收
     *
     */
    public static void gc() {
    //實際調用的是Runtime的相應方法
 Runtime.getRuntime().gc();
    }

    /**
     *
     * 調用所有失效對象的finalize方法
     *
     */
    public static void runFinalization() {
    //實際調用的是Runtime的相應方法
 Runtime.getRuntime().runFinalization();
    }

    /**
     * @deprecated
     */
    public static void runFinalizersOnExit(boolean value) {
    //實際調用的是Runtime的相應方法  
 Runtime.getRuntime().runFinalizersOnExit(value);
    }

    /**
     *
     * Loads a code file with the specified filename from the local file
     * system as a dynamic library. The filename
     * argument must be a complete path name.
     *
     */
    public static void load(String filename) {
    //實際調用的是Runtime的方法 
 Runtime.getRuntime().load0(getCallerClass(), filename);
    }

    /**
     *
     * 載入動態連結程式庫
     *
     */
    public static void loadLibrary(String libname) {
 Runtime.getRuntime().loadLibrary0(getCallerClass(), libname);
    }

    /**
     * Maps a library name into a platform-specific string representing
     * a native library.
     */
    public static native String mapLibraryName(String libname);

    private static InputStream nullInputStream() throws NullPointerException {
    //正常返回null
 if (currentTimeMillis() > 0)
     return null;
 
 //currentTimeMillis不大於0拋出異常
 throw new NullPointerException();
    }

    private static PrintStream nullPrintStream() throws NullPointerException {
    //正常返回null
 if (currentTimeMillis() > 0)
     return null;
 
 //currentTimeMillis不大於0拋出異常
 throw new NullPointerException();
    }

    /**
     * Initialize the system class.  Called after thread initialization.
     *
     * 初始化System類,線上程初始化後調用
     */
    private static void initializeSystemClass() {
    //建立一個空的Properties,並賦給當前屬性對象
 props = new Properties();
 //用預設初始化System屬性
 initProperties(props);
 
 sun.misc.Version.init();
 
 //初始化標準輸入,標準輸出,標準錯誤
 FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
 FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
 FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
 
 setIn0(new BufferedInputStream(fdIn));
 setOut0(new PrintStream(new BufferedOutputStream(fdOut, 128), true));
 setErr0(new PrintStream(new BufferedOutputStream(fdErr, 128), true));

 loadLibrary("zip");

        Terminator.setup();
       
    //設定最大記憶體數
  sun.misc.VM.maxDirectMemory();

 sun.misc.VM.booted();
    }

    //擷取調用者的Class對象
    static Class getCallerClass() {
        // NOTE use of more generic Reflection.getCallerClass()
        return Reflection.getCallerClass(3);
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.