简介
- System类,是Java中一个比较常用的类,其使用到的方法也比较少。
-
源码阅读
public final class System {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;public static Console console() {if (cons == null) {synchronized (System.class) {cons = sun.misc.SharedSecrets.getJavaIOAccess().console();}}return cons;}// 管道流public static Channel inheritedChannel() throws IOException {return SelectorProvider.provider().inheritedChannel();}// 安全管理 IOprivate 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) {sm.checkPermission(new RuntimePermission("setSecurityManager"));}if ((s != null) && (s.getClass().getClassLoader() != null)) {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;}// 本地方法 获取从 1970年1月1日0点0分0秒 到当前之间的毫秒数public static native long currentTimeMillis();// 本地方法 获取从 1970年1月1日0点0分0秒 到当前之间的纳秒数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);// Properties对象private static Properties props;// 初始化 Properties 对象private static native Properties initProperties(Properties props);// 获取Properties对象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;}// 通过key或者当前对象的 Properties 对象的keypublic static String getProperty(String key) {checkKey(key);SecurityManager sm = getSecurityManager();if (sm != null) {sm.checkPropertyAccess(key);}return props.getProperty(key);}// 根据 k v 获取public static String getProperty(String key, String def) {checkKey(key);SecurityManager sm = getSecurityManager();if (sm != null) {sm.checkPropertyAccess(key);}return props.getProperty(key, def);}// 设置 k vpublic 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);}// 删除 某个keypublic 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);}// 获得指定的环境变量的键值对Map对象public static java.util.Map<String,String> getenv() {SecurityManager sm = getSecurityManager();if (sm != null) {sm.checkPermission(new RuntimePermission("getenv.*"));}return ProcessEnvironment.getenv();}// 退出程序的方法public static void exit(int status) {Runtime.getRuntime().exit(status);}// 调用gc方法,但是JVM不一定立即执行GCpublic static void gc() {Runtime.getRuntime().gc();}// 运行挂起终止的任何对象的终止方法。public static void runFinalization() {Runtime.getRuntime().runFinalization();}// 终止方法 已经过时public static void runFinalizersOnExit(boolean value) {Runtime.runFinalizersOnExit(value);}// 加载一个文件public static void load(String filename) {Runtime.getRuntime().load0(Reflection.getCallerClass(), filename);}// 加载类包public static void loadLibrary(String libname) {Runtime.getRuntime().loadLibrary0(Reflection.getCallerClass(), libname);}// 调用本地方法 根据类包获取名字 win10 下是 包的dll文件public static native String mapLibraryName(String libname);// 获取一个打印流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);}// System类的初始化private static void initializeSystemClass() {props = new Properties();initProperties(props); // initialized by the VMsun.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")));loadLibrary("zip");Terminator.setup();sun.misc.VM.initializeOSEnvironment();Thread current = Thread.currentThread();current.getThreadGroup().add(current);setJavaLangAccess();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();}});}}
常用的方法
如果我们需要在项目启动的时候,设置运行环境,我们就可以读取配置,然后写入 ```java public class SystemTest { public static void main(String[] args) {
String s = System.setProperty("key", "value"); System.out.println(s); System.out.println(System.getProperty("key"));} }
```
