System 源码

匿名 (未验证) 提交于 2019-12-03 00:26:01
java.lang.System

System类包含几个有用的类字段和方法。 它不能被实例化。

System类提供的System包括标准输入,标准输出和错误输出流; 访问外部定义的属性和环境变量; 一种加载文件和库的方法; 以及用于快速复制阵列的一部分的实用方法。

public final static PrintStream err = null;//“标准”错误输出流。
public final static InputStream in = null;//“标准”输入流。
public final static PrintStream out = null;//“标准”输出流。

/*  * 版权所有(c)1994,2013,Oracle和/或其附属公司。 版权所有。 ORACLE专有/保密。 使用受制于许可条款。  */ package java.lang;  import java.io.*; import java.lang.reflect.Executable; import java.lang.annotation.Annotation; import java.security.AccessControlContext; import java.util.Properties; import java.util.PropertyPermission; import java.util.StringTokenizer; import java.util.Map; import java.security.AccessController; import java.security.PrivilegedAction; import java.security.AllPermission; import java.nio.channels.Channel; import java.nio.channels.spi.SelectorProvider; import sun.nio.ch.Interruptible; import sun.reflect.CallerSensitive; import sun.reflect.Reflection; import sun.security.util.SecurityConstants; import sun.reflect.annotation.AnnotationType;  /**  * 系统类包含几个有用的类字段和方法。它不能被实例化。  */ public final class System {      /*       * 通过静态初始化器注册本机。      * VM将调用initializeSystemClass方法来完成这个与clinit分离的类的初始化。注意,要使用VM设置的属性,请参阅initializeSystemClass方法中描述的约束。      */     private static native void registerNatives();     static {         registerNatives();     }      /** 不要让任何人实例化这个类 */     private System() {     }      /**      * “标准”输入流。       */     public final static InputStream in = null;      /**      * “标准”输出流。       */     public final static PrintStream out = null;      /**      * “标准”错误输出流。       */     public final static PrintStream err = null;      /* 系统的安全管理器。      */     private static volatile 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 volatile Console cons = null;     /**      * 返回与当前Java虚拟机关联的唯一的Console对象(如果有)。       */      public static Console console() {          if (cons == null) {              synchronized (System.class) {                  cons = sun.misc.SharedSecrets.getJavaIOAccess().console();              }          }          return cons;      }      /**      * 返回从创建此Java虚拟机的实体继承的通道。       */     public static Channel inheritedChannel() throws IOException {         return SelectorProvider.provider().inheritedChannel();     }      private static void checkIO() {         SecurityManager sm = getSecurityManager();         if (sm != null) {             sm.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 {             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;     }      /**      * 获取系统安全界面。       */     public static SecurityManager getSecurityManager() {         return security;     }      /**      * 返回当前时间(以毫秒为单位)。       */     public static native long currentTimeMillis();      /**      * 以纳秒为单位返回正在运行的Java虚拟机的高分辨率时间源的当前值。       */     public static native long nanoTime();      /**      * 将指定源数组中的数组从指定位置复制到目标数组的指定位置。       */     public static native void arraycopy(Object src,  int  srcPos, Object dest, int destPos, int length);      /**      * 返回与默认方法hashCode()返回的给定对象相同的哈希码,无论给定对象的类是否覆盖了hashCode()。       */     public static native int identityHashCode(Object x);      /**      * 系统属性。下面的属性保证被定义:      */     private static Properties props;     private static native Properties initProperties(Properties props);      /**      * 确定当前的系统属性。      */     public static Properties getProperties() {         SecurityManager sm = getSecurityManager();         if (sm != null) {             sm.checkPropertiesAccess();         }          return props;     }      /**      * 返回与系统相关的行分隔符字符串。       */     public static String lineSeparator() {         return lineSeparator;     }      private static String lineSeparator;      /**      * 将系统属性设置为 Properties参数。       */     public static void setProperties(Properties props) {         SecurityManager sm = getSecurityManager();         if (sm != null) {             sm.checkPropertiesAccess();         }         if (props == null) {             props = new Properties();             initProperties(props);         }         System.props = props;     }      /**      * 获取指定键指示的系统属性。      */     public static String getProperty(String key) {         checkKey(key);         SecurityManager sm = getSecurityManager();         if (sm != null) {             sm.checkPropertyAccess(key);         }          return props.getProperty(key);     }      /**      * 获取指定键指示的系统属性。       */     public static String getProperty(String key, String def) {         checkKey(key);         SecurityManager sm = getSecurityManager();         if (sm != null) {             sm.checkPropertyAccess(key);         }          return props.getProperty(key, def);     }      /**      * 设置由指定键指示的系统属性。       */     public static String setProperty(String key, String value) {         checkKey(key);         SecurityManager sm = getSecurityManager();         if (sm != null) {             sm.checkPermission(new PropertyPermission(key,                 SecurityConstants.PROPERTY_WRITE_ACTION));         }          return (String) props.setProperty(key, value);     }      /**      * 删除指定键指定的系统属性。       */     public static String clearProperty(String key) {         checkKey(key);         SecurityManager sm = getSecurityManager();         if (sm != null) {             sm.checkPermission(new PropertyPermission(key, "write"));         }          return (String) props.remove(key);     }      private static void checkKey(String key) {         if (key == null) {             throw new NullPointerException("key can't be null");         }         if (key.equals("")) {             throw new IllegalArgumentException("key can't be empty");         }     }      /**      * 获取指定环境变量的值。       */     public static String getenv(String name) {         SecurityManager sm = getSecurityManager();         if (sm != null) {             sm.checkPermission(new RuntimePermission("getenv."+name));         }          return ProcessEnvironment.getenv(name);     }       /**      *  返回当前系统环境的不可修改的字符串映射视图。      */     public static java.util.Map<String,String> getenv() {         SecurityManager sm = getSecurityManager();         if (sm != null) {             sm.checkPermission(new RuntimePermission("getenv.*"));         }          return ProcessEnvironment.getenv();     }      /**      * 终止当前运行的Java虚拟机。       */     public static void exit(int status) {         Runtime.getRuntime().exit(status);     }      /**      * 运行垃圾回收器。       */     public static void gc() {         Runtime.getRuntime().gc();     }      /**      * 运行任何对象等待定稿的最终化方法。       */     public static void runFinalization() {         Runtime.getRuntime().runFinalization();     }      /**      * 已弃用       * 这种方法本质上是不安全的。 它可能导致在活动对象上调用finalizer,而其他线程同时操作这些对象,导致不稳定的行为或死锁。       */     @Deprecated     public static void runFinalizersOnExit(boolean value) {         Runtime.runFinalizersOnExit(value);     }      /**      * 加载由filename参数指定的本机库。       */     @CallerSensitive     public static void load(String filename) {         Runtime.getRuntime().load0(Reflection.getCallerClass(), filename);     }      /**      * 加载 libname参数指定的本机库。       */     @CallerSensitive     public static void loadLibrary(String libname) {         Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);     }      /**      * 将库名称映射到表示本地库的平台特定字符串。       */     public static native String mapLibraryName(String libname);      /**      * 为stdout/err创建基于编码的PrintStream。      */     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);     }       /**      * 初始化系统类。之后调用线程初始化。      */     private static void initializeSystemClass() {          /**         * VM可能会调用JNU_NewStringPlatform()来在“props”初始化期间设置那些编码敏感属性         * (user.home,user.name,boot.class.path等),在此过程中可能需要通过         * System.getProperty() 到在初始化初期初始化(放入“道具”)的相关系统编码属性。          * 因此,确保“props”在初始化开始时可用,并且所有系统属性都可直接加入。         */         props = new Properties();         initProperties(props);  // 由VM初始化          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")));          // 现在加载zip库,以防止java.util.zip.ZipFile尝试使用它自己来稍后加载该库。         loadLibrary("zip");          // 为HUP、TERM和INT(如有)设置Java信号处理程序。         Terminator.setup();          /**         *  初始化需要为类库设置的任何不正常的操作系统设置。          *  目前,除了在使用java.io类之前设置进程范围错误模式的Windows之外,这是无处不在的。         */         sun.misc.VM.initializeOSEnvironment();          // 主线程不像其他线程那样添加到它的线程组中;我们必须自己做这件事。         Thread current = Thread.currentThread();         current.getThreadGroup().add(current);          // 注册共享秘密         setJavaLangAccess();          /**         * 在初始化过程中调用的子系统可以调用sun.misc.VM.isBooted(),         * 以避免在应用程序类加载器设置完成之前进行操作。 重要提示:确保这仍然是最后的初始化操作!         */         sun.misc.VM.booted();     }      private static void setJavaLangAccess() {         // 允许java.lang之外的特权类         sun.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();             }         });     } } 
文章来源: System 源码
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!