System中代表程序所在系统,提供了对应的一些系统属性信息,和系统操作。
System类不能手动创建对象,因为构造方法被private修饰,阻止外界创建对象。System类中的都是static方法,类名访问即可。在JDK中,有许多这样的类。
常见应用场景:
1. 获取系统当前Epoch时间:System.currentTimeMillis()
//打印程序执行时间public void runningTime(){long start = System.currentTimeMillis();//当前Epoch时间xfor(int i = 0 ; i < 10000; i++){System.out.println(i);}long end = System.currentTimeMillis();//当前Epoch时间ySystem.out.println(end - start);//当前时间y-当前时间x}
2. 终止程序,退出JVM:System.exit(int exitcode)
3. 垃圾回收:System.gc()
public class Person {public void finalize(){System.out.println("垃圾收取了");}}/** JVM在内存中,收取对象的垃圾* 当没有更多引用指向该对象时,会自动调用垃圾回收机制回收堆中的对象* 同时调用回收对象所属类的finalize方法()* static void gc()*/public static void gcTest(){new Person();new Person();new Person();new Person();new Person();new Person();new Person();new Person();System.gc();}
4. 获取JVM的环境变量:System.getProperty()
一般我们用它去看如下属性:
- os.name 操作系统
- java.class.path Java的classpath
- java.library.path 加载library时搜素的路径列表
- user.name 程序当前执行用户
- user.home 用户的家目录
user.dir 用户当前的工作目录
String username = System.getProperty("user.name"); //henryliString userhome = System.getProperty("user.home"); //Users/henryliString userdir = System.getProperty("user.dir"); //Users/henryli/Documents/GitHub/JavaBasicPracticeString osname = System.getProperty("os.name"); //Mac OS X
5. 获取操作系统 Environment Variables
public static String getenv(String name):获得指定环境变量的值public static Map<String, String> getenv():获得所有环境变量的mapString path = System.getenv("PATH");System.out.println(path);Map<String,String> envMap = System.getenv();System.out.println(envMap);
6. 复制数组:arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
public static void copyArray(){int[] src = {11,22,33,44,55,66};int[] desc = {77,88,99,0};System.arraycopy(src, 1, desc, 1, 2);//将src数组的1位置开始(包含1位置)的两个元素,拷贝到desc的1,2位置上System.out.println(Arrays.toString(desc));}
