JDK源碼解析之 java.lang.System

一個和系統環境進行交互的類.
System不允許被實例化, 而且是一個final類

一、不能實例化

private System() {
}

二、成員變量

public final static InputStream in = null;	//這是“標準”輸入流。
public final static PrintStream out = null;	//這是“標準”輸出流。
public final static PrintStream err = null;	//這是“標準”錯誤輸出流。private static native void setIn0(InputStream in);private static native void setOut0(PrintStream out);private static native void setErr0(PrintStream err);

定義的三個IO流,都是final修飾符,所以即使是public 也是不能重新賦值。

三、常用方法

1、關于SecurityManager

/*** The security manager for the system.*/private static volatile SecurityManager security = null;private static void checkIO() {SecurityManager sm = getSecurityManager();if (sm != null) {sm.checkPermission(new RuntimePermission("setIO"));}}public static void setSecurityManager(final SecurityManager s) {try {s.checkPackageAccess("java.lang");} catch (Exception e) {// no-op}setSecurityManager0(s);}private static synchronized void setSecurityManager0(final SecurityManager s) {SecurityManager sm = getSecurityManager();if (sm != null) {// ask the currently installed security manager if we// can replace it.sm.checkPermission(new RuntimePermission("setSecurityManager"));}if ((s != null) && (s.getClass().getClassLoader() != null)) {// New security manager class is not on bootstrap classpath.// Cause policy to get initialized before we install the new// security manager, in order to prevent infinite loops when// trying to initialize the policy (which usually involves// accessing some security and/or system properties, which in turn// calls the installed security manager's checkPermission method// which will loop infinitely if there is a non-system class// (in this case: the new security manager class) on the stack).AccessController.doPrivileged(new PrivilegedAction<Object>() {public Object run() {s.getClass().getProtectionDomain().implies(SecurityConstants.ALL_PERMISSION);return null;}});}security = s;}/*** Gets the system security interface.** @return if a security manager has already been established for the current*         application, then that security manager is returned; otherwise,*         <code>null</code> is returned.* @see #setSecurityManager*/public static SecurityManager getSecurityManager() {return security;}

System類定義了安全管理器,并且【volatile】修飾該變量。在初始化IO流時,需要使用安全器校驗權限。

2、關于console

控制臺定義console

private static volatile Console cons = null;/*** Returns the unique {@link java.io.Console Console} object associated* with the current Java virtual machine, if any.** @return  The system console, if any, otherwise <tt>null</tt>.** @since   1.6*/public static Console console() {if (cons == null) {synchronized (System.class) {cons = sun.misc.SharedSecrets.getJavaIOAccess().console();}}return cons;}

System中的console是通過【sun.misc.SharedSecrets】類獲取得到的。關于SharedSecrets類這里只能簡單說是關于jvm的

3、currentTimeMillis和nanoTime

獲取系統時間方法

/*** 獲取毫秒級的時間戳(1970年1月1日0時起的毫秒數)*/
public static native long currentTimeMillis();
/*** 獲取納秒,返回的可能是任意時間(主要用于衡量時間段)*/
public static native long nanoTime();

4、arraycopy方法

該復制為淺復制,即對象數組,只復制對象引用。

public static native void arraycopy(Object src,  int  srcPos,Object dest, int destPos,int length);

5、identityHashCode 方法

返回對象地址方法

public static native int identityHashCode(Object x);

6、加載動態庫library

@CallerSensitivepublic static void load(String filename) {Runtime.getRuntime().load0(Reflection.getCallerClass(), filename);}/***/@CallerSensitivepublic static void loadLibrary(String libname) {Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);}/*** Maps a library name into a platform-specific string representing* a native library.** @param      libname the name of the library.* @return     a platform-dependent native library name.* @exception  NullPointerException if <code>libname</code> is*             <code>null</code>* @see        java.lang.System#loadLibrary(java.lang.String)* @see        java.lang.ClassLoader#findLibrary(java.lang.String)* @since      1.2*/public static native String mapLibraryName(String libname);

7、初始化Java class

/*** Create PrintStream for stdout/err based on encoding.*/private static PrintStream newPrintStream(FileOutputStream fos, String enc) {if (enc != null) {try {return new PrintStream(new BufferedOutputStream(fos, 128), true, enc);} catch (UnsupportedEncodingException uee) {}}return new PrintStream(new BufferedOutputStream(fos, 128), true);}/*** Initialize the system class.  Called after thread initialization.*/private static void initializeSystemClass() {// VM might invoke JNU_NewStringPlatform() to set those encoding// sensitive properties (user.home, user.name, boot.class.path, etc.)// during "props" initialization, in which it may need access, via// System.getProperty(), to the related system encoding property that// have been initialized (put into "props") at early stage of the// initialization. So make sure the "props" is available at the// very beginning of the initialization and all system properties to// be put into it directly.props = new Properties();initProperties(props);  // initialized by the VM// There are certain system configurations that may be controlled by// VM options such as the maximum amount of direct memory and// Integer cache size used to support the object identity semantics// of autoboxing.  Typically, the library will obtain these values// from the properties set by the VM.  If the properties are for// internal implementation use only, these properties should be// removed from the system properties.//// See java.lang.Integer.IntegerCache and the// sun.misc.VM.saveAndRemoveProperties method for example.//// Save a private copy of the system properties object that// can only be accessed by the internal implementation.  Remove// certain system properties that are not intended for public access.sun.misc.VM.saveAndRemoveProperties(props);lineSeparator = props.getProperty("line.separator");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(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding")));// Load the zip library now in order to keep java.util.zip.ZipFile// from trying to use itself to load this library later.loadLibrary("zip");// Setup Java signal handlers for HUP, TERM, and INT (where available).Terminator.setup();// Initialize any miscellenous operating system settings that need to be// set for the class libraries. Currently this is no-op everywhere except// for Windows where the process-wide error mode is set before the java.io// classes are used.sun.misc.VM.initializeOSEnvironment();// The main thread is not added to its thread group in the same// way as other threads; we must do it ourselves here.Thread current = Thread.currentThread();current.getThreadGroup().add(current);// register shared secretssetJavaLangAccess();sun.misc.VM.booted();}private static void setJavaLangAccess() {// Allow privileged classes outside of java.langsun.misc.SharedSecrets.setJavaLangAccess(new sun.misc.JavaLangAccess(){public sun.reflect.ConstantPool getConstantPool(Class<?> klass) {return klass.getConstantPool();}public boolean casAnnotationType(Class<?> klass, AnnotationType oldType, AnnotationType newType) {return klass.casAnnotationType(oldType, newType);}public AnnotationType getAnnotationType(Class<?> klass) {return klass.getAnnotationType();}public Map<Class<? extends Annotation>, Annotation> getDeclaredAnnotationMap(Class<?> klass) {return klass.getDeclaredAnnotationMap();}public byte[] getRawClassAnnotations(Class<?> klass) {return klass.getRawAnnotations();}public byte[] getRawClassTypeAnnotations(Class<?> klass) {return klass.getRawTypeAnnotations();}public byte[] getRawExecutableTypeAnnotations(Executable executable) {return Class.getExecutableTypeAnnotationBytes(executable);}public <E extends Enum<E>>E[] getEnumConstantsShared(Class<E> klass) {return klass.getEnumConstantsShared();}public void blockedOn(Thread t, Interruptible b) {t.blockedOn(b);}public void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook) {Shutdown.add(slot, registerShutdownInProgress, hook);}public int getStackTraceDepth(Throwable t) {return t.getStackTraceDepth();}public StackTraceElement getStackTraceElement(Throwable t, int i) {return t.getStackTraceElement(i);}public String newStringUnsafe(char[] chars) {return new String(chars, true);}public Thread newThreadWithAcc(Runnable target, AccessControlContext acc) {return new Thread(target, acc);}public void invokeFinalize(Object o) throws Throwable {o.finalize();}});}

四、拓展

1、java 能否自己寫一個類叫 java.lang.System

一般情況下是不可以的,但是可以通過特殊的處理來達到目的,這個特殊的處理就是自己寫個類加載器來加載自己寫的這個java.lang.System

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/535729.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/535729.shtml
英文地址,請注明出處:http://en.pswp.cn/news/535729.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

詳解MySQL中DROP,TRUNCATE 和DELETE的區別

注意:這里說的delete是指不帶where子句的delete語句 相同點: truncate和不帶where子句的delete, 以及drop都會刪除表內的數據 不同點: 1. truncate和 delete只刪除數據不刪除表的結構(定義) drop語句將刪除表的結構被依賴的約束(constrain),觸發器(trigger),索引(index…

JDK源碼解析之 Java.lang.Package

如果我們在Class對象上調用getPackage方法&#xff0c;就可以得到描述該類所在包的Package對象(Package類是在java.lang中定義的)。我們也可以用包名通過調用靜態方法getPackage或者調用靜態方法getPackages(該方法返回由系統中所有已知包構成的數組)來獲得Package對象。getNam…

Mysql中limit的用法詳解

在我們使用查詢語句的時候&#xff0c;經常要返回前幾條或者中間某幾行數據&#xff0c;這個時候怎么辦呢&#xff1f;不用擔心&#xff0c;mysql已經為我們提供了這樣一個功能。SELECT * FROM table LIMIT [offset,] rows | rows OFFSET offset LIMIT 子句可以被用于強制 SE…

Docker入門-簡介

獨具魅力的Docker作為一門新技術&#xff0c;它的出現有可能引起其所在領域大范圍的波動甚至是重新洗牌。根據業內專業人士的看法&#xff0c;不論如何&#xff0c;Docker的出現&#xff0c;已經成為云服務市場中一枚極具意義的戰略性棋子。從2013年開始在國內發力&#xff0c;…

Mysql中limit的優化

在一些情況中&#xff0c;當你使用LIMIT row_count而不使用HAVING時&#xff0c;MySQL將以不同方式處理查詢。 如果你用LIMIT只選擇一些行&#xff0c;當MySQL選擇做完整的表掃描時&#xff0c;它將在一些情況下使用索引。 如果你使用LIMIT row_count與ORD…

Docker入門-架構

Docker 包括三個基本概念: 鏡像&#xff08;Image&#xff09;&#xff1a;Docker 鏡像&#xff08;Image&#xff09;&#xff0c;就相當于是一個 root 文件系統。比如官方鏡像 ubuntu:16.04 就包含了完整的一套 Ubuntu16.04 最小系統的 root 文件系統。容器&#xff08;Cont…

MYSQL出錯代碼列表大全(中文)

mysql出錯了,以前往往靠猜.現在有了這張表,一查就出來了. 1005&#xff1a;創建表失敗1006&#xff1a;創建數據庫失敗1007&#xff1a;數據庫已存在&#xff0c;創建數據庫失敗1008&#xff1a;數據庫不存在&#xff0c;刪除數據庫失敗1009&#xff1a;不能刪除數據庫文件導致…

Docker入門-安裝

Centos7下安裝Docker docker官方說至少Linux 內核3.8 以上&#xff0c;建議3.10以上&#xff08;ubuntu下要linux內核3.8以上&#xff0c; RHEL/Centos 的內核修補過&#xff0c; centos6.5的版本就可以&#xff09; 1、把yum包更新到最新&#xff1a;yum update 2、安裝需要的…

Docker原理之Namespaces

命名空間&#xff08;namespaces&#xff09;是 Linux 為我們提供的用于分離進程樹、網絡接口、掛載點以及進程間通信等資源的方法。 一、Namespaces 在日常使用 Linux 或者 macOS 時&#xff0c;我們并沒有運行多個完全分離的服務器的需要&#xff0c;但是如果我們在服務器上啟…

mysql 快速插入(insert)多條記錄

方法1: INSERT INTO table(col_1, col_2,col_3) VALUES(1,11,111); INSERT INTO table(col_1, col_2,col_3)   VALUES(2,22,222); INSERT INTO table(col_1, col_2,col_3)   VALUES(3,33,333); 有沒有更快捷的辦法呢?答案是有(見方法2) 方法2: INSERT INTO table(col…

Docker原理之CGroups

控制組&#xff08;cgroups&#xff09;是 Linux 內核的一個特性&#xff0c;主要用來對共享資源進行隔離、限制、審計 等。只有能控制分配到容器的資源&#xff0c;才能避免當多個容器同時運行時的對系統資源的競爭。控制組技術最早是由 Google 的程序員 2006 年起提出&#x…

Mysql中的轉義字符

字符串是多個字符組成的一個字符序列&#xff0c;由單引號( “”) 或雙引號 ( “"”) 字符包圍。(但在 ANSI 模式中運行時只能用單引號)。 例如&#xff1a; a string"another string"在一個字符串中&#xff0c;如果某個序列具有特殊的含義&#xff0c;每個序…

Docker原理之UnionFS

一、UnionFS Linux 的命名空間和控制組分別解決了不同資源隔離的問題&#xff0c;前者解決了進程、網絡以及文件系統的隔離&#xff0c;后者實現了 CPU、內存等資源的隔離&#xff0c;但是在 Docker 中還有另一個非常重要的問題需要解決 - 也就是鏡像。 鏡像到底是什么&#…

教你精確編寫高質量高性能的MySQL語法

在應用系統開發初期&#xff0c;由于開發數據庫數據比較少&#xff0c;對于查詢SQL語句&#xff0c;復雜視圖的編寫&#xff0c;剛開始不會體會出SQL語句各種寫法的性能優劣&#xff0c;但是如果將應用系統提交實際應用后&#xff0c;隨著數據庫中數據的增加&#xff0c;系統的…

Docker使用-Hello World

1、docker pull hello-world 拉去docker遠程倉庫中的Hello World的鏡像 [rootCarlota2 ~]# docker pull hello-world Using default tag: latest latest: Pulling from library/hello-world 0e03bdcc26d7: Pull complete Digest: sha256:7f0a9f93b4aa3022c3a4c147a449bf11e09…

Mysql數據庫引擎快速指南

如果你是個賽車手并且按一下按鈕就能夠立即更換引擎而不需要把車開到車庫里去換&#xff0c;那會是怎么感覺呢&#xff1f; MySQL 數據庫為開發人員所做的就好像是按按鈕換引擎&#xff1b;它讓你選擇數據庫引擎&#xff0c;并給你一條簡單的途徑來切換它。 MySQL的自帶引擎肯…

Docker使用-構建MySQL

拉取官方鏡像&#xff08;我們這里選擇5.7&#xff0c;如果不寫后面的版本號則會自動拉取最新版&#xff09; docker pull mysql:5.7 # 拉取 mysql 5.7 docker pull mysql # 拉取最新版mysql鏡像MySQL文檔地址 檢查是否拉取成功 $ sudo docker images一般來說數據庫容…

Java集合:什么是Java集合?

一、集合的由來 通常&#xff0c;我們的Java程序需要根據程序運行時才知道創建了多少個對象。但若非程序運行&#xff0c;程序開發階段&#xff0c;我們根本不知道到底需要多少個數量的對象&#xff0c;甚至不知道它的準確類型。為了滿足這些常規的編程需要&#xff0c;我們要…

Mysql截取中英數混合的字符串

在 mysql中截取字符串我們用 LEFT函數 LEFT(str,len) 返回從字符串str 開始的len 最左字符。 mysql> SELECT LEFT(foobarbar, 5); -> fooba 手冊上只介紹了截取英文字符串的方法&#xff0c;中文或者中英文的怎么辦呢&#xff1f;以下是截取中英混合的字符串(中國人…

Java集合:Collection接口

Collection是一個接口&#xff0c;繼承自Iterable。我們先看一下Iterable接口的源碼 一、Iterable package java.lang;import java.util.Iterator; import java.util.Objects; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Cons…