System
public class SystemTest {
public static void main(String[] args) throws Exception {
// 获取系统的所有环境变量
Map<String, String> env = System.getenv();
for(String name : env.keySet()){
System.out.println(name + " ---> " + env.get(name));
}
//获取指定环境变量的值
System.out.println("JAVA_HOME: "+System.getenv("JAVA_HOME"));
//获取所有的系统属性
Properties sysProps = System.getProperties();
sysProps.store(new FileOutputStream("sysprops.txt"), "System Properties");
//获取指定的系统属性
System.out.println(System.getProperty("os.name"));
}
}
Runtime
package learn.runtime;
import java.io.IOException;
public class RuntimeTest {
public static void main(String[] args) {
Runtime runtime = Runtime.getRuntime();
System.out.println("处理器的数量:"+runtime.availableProcessors());
System.out.println("空闲内存数:"+runtime.freeMemory());
System.out.println("总内存数:"+runtime.totalMemory());
System.out.println("可用最大内存:"+runtime.maxMemory());
// 运行一个exe
try {
runtime.exec("notepad.exe D:/mysql.sql");
} catch (IOException e) {
e.printStackTrace();
}
}
}
自定义类实现“克隆”
步骤如下:
(1)自定义类实现 Cloneable接口。这是一个标记性的接口,实现该接口的对象可以实现“自我克隆”,接口里没有定义任何方法。
(2)自定义类实现自己的 clone()方法。
(3)实现 clone()方法时通过 super clone:调用 Object 实现的 clone方法来得到该对象的副本,并返回该副本。
如下程序示范了如何实现“自我克隆”。
package test;
class Address{
private String detail;
public Address(String detail){
this.detail = detail;
}
}
class User implements Cloneable{
private int age;
Address addr;
public User(int age){
this.age = age;
addr = new Address("广州天河");
}
// 通过调用super的clone,是浅拷贝
public User clone()
throws CloneNotSupportedException
{
return (User) super.clone();
}
}
public class TestDemo {
public static void main(String[] args) throws CloneNotSupportedException {
User u1 = new User(18);
User u2 = u1.clone();
System.out.println(u1 == u2);//false
System.out.println(u1.addr == u2.addr);//true
}
}
如图:
Objects
Java7新增了一个 Objects工具类,它提供了一些工具方法来操作对象,这些工具方法大多是“空指针”安全的。
比如,你不能明确地判断一个引用变量是否为mull,如果贸然地调用该变量的 tostring0方法,则可能引发 Nullpointerexcetpion异常;但如果使用 Objects类提供的 tostring( Object o)方法,就不会引发空指针异常,当o为null时,程序将返回一个"null"字符串。
提示:
Java为工具类的命名习惯是添加一个字母s,比如操作数组的工具类是 Arrays,操作集合的工具类是 Collections
如下程序示范了 Objects工具类的用法。
public class TestDemo {
static TestDemo obj;//默认值是null
public static void main(String[] args) throws CloneNotSupportedException {
System.out.println(Objects.hashCode(obj));//0
System.out.println(Objects.toString(obj));//null
String s = "jerry";
System.out.println(Objects.equals(obj, s));//false
Objects.requireNonNull(obj, "obj参数不能为null");//若obj是null,则抛异常
}
}