好多编程语言都提供了和系统的相关操作方法,JAVA也不例外。JAVA中常用的系统方法有:
static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) // Copies an array from the specified source array, beginning at the specified position, to the specified position of the destination array.
static String clearProperty(String key) // Removes the system property indicated by the specified key.
static Console console() // Returns the unique Console object associated with the current Java virtual machine, if any.
static long currentTimeMillis() // Returns the current time in milliseconds.
static void exit(int status) // Terminates the currently running Java Virtual Machine.
static void gc() // Runs the garbage collector in the Java Virtual Machine.
static Map<String,String> getenv() // Returns an unmodifiable string map view of the current system environment.
static String getenv(String name) // Gets the value of the specified environment variable.
static System.Logger getLogger(String name) // Returns an instance of Logger for the caller's use.
static System.Logger getLogger(String name, ResourceBundle bundle) // Returns a localizable instance of Logger for the caller's use.
static Properties getProperties() // Determines the current system properties.
static String getProperty(String key) // Gets the system property indicated by the specified key.
static String getProperty(String key, String def) // Gets the system property indicated by the specified key.
static SecurityManager getSecurityManager() // Deprecated, for removal: This API element is subject to removal in a future version.This method is only useful in conjunction with the Security Manager, which is deprecated and subject to removal in a future release.
static int identityHashCode(Object x) // Returns the same hash code for the given object as would be returned by the default method hashCode(), whether or not the given object's class overrides hashCode().
static Channel inheritedChannel() // Returns the channel inherited from the entity that created this Java virtual machine.
static String lineSeparator() // Returns the system-dependent line separator string.
static void load(String filename) // Loads the native library specified by the filename argument.
static void loadLibrary(String libname) // Loads the native library specified by the libname argument.
static String mapLibraryName(String libname) // Maps a library name into a platform-specific string representing a native library.
static long nanoTime() // Returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds.
static void runFinalization() // Deprecated, for removal: This API element is subject to removal in a future version.Finalization has been deprecated for removal.
static void setErr(PrintStream err) // Reassigns the "standard" error output stream.
static void setIn(InputStream in) // Reassigns the "standard" input stream.
static void setOut(PrintStream out) // Reassigns the "standard" output stream.
static void setProperties(Properties props) // Sets the system properties to the Properties argument.
static String setProperty(String key, String value) // Sets the system property indicated by the specified key.
static void setSecurityManager(SecurityManager sm) // Deprecated, for removal: This API element is subject to removal in a future version.This method is only useful in conjunction with the Security Manager, which is deprecated and subject to removal in a future release.
比如常见的统计操作计算时间:
public class Demo {
public static void main(String[] args) throws Exception {
long tic = System.currentTimeMillis();
String str = "";
for(int i = 0;i < 10000000;++i) {}
long toc = System.currentTimeMillis();
System.out.println("TIME IS " + (toc - tic));
}
}
上面的时间单位为ms。
同时上边System中也存在gc方法:
/**
* Runs the garbage collector in the Java Virtual Machine.
* <p>
* Calling the {@code gc} method suggests that the Java Virtual Machine
* expend effort toward recycling unused objects in order to
* make the memory they currently occupy available for reuse
* by the Java Virtual Machine.
* When control returns from the method call, the Java Virtual Machine
* has made a best effort to reclaim space from all unused objects.
* There is no guarantee that this effort will recycle any particular
* number of unused objects, reclaim any particular amount of space, or
* complete at any particular time, if at all, before the method returns or ever.
* There is also no guarantee that this effort will determine
* the change of reachability in any particular number of objects,
* or that any particular number of {@link java.lang.ref.Reference Reference}
* objects will be cleared and enqueued.
*
* <p>
* The call {@code System.gc()} is effectively equivalent to the
* call:
* <blockquote><pre>
* Runtime.getRuntime().gc()
* </pre></blockquote>
*
* @see java.lang.Runtime#gc()
*/
public static void gc() {
Runtime.getRuntime().gc();
}
从上面的结果来看,System中的gc方法其实还是Runtime中的gc方法。
同时在C/C++中还存在一个析构函数的概念,构造方法在对象构造时调用,析构方法在对象被销毁时调用,而在C/C++可以主动free/delete某个对象,这样就调用了析构方法。而在JAVA中的实例化对象的回收是由JVM自动进行的,那么如果想要在对象被销毁或回收时进行某种操作的话,就可以使用下面的方法:
protected void finalize() throws Throwable
可以测试一下上面的方法:
class A {
public A() {
System.out.println("Constructor");
}
protected void finalize() throws Throwable {
System.out.println("finalize");
}
}
public class Demo {
public static void main(String[] args) throws Exception {
A a = new A();
a = null;
System.gc();
}
}
执行结果为:
Constructor
finalize
上边的finalize从某种意义上表示了析构方法的操作,而之所以throws出的是Throwable表示不论出现Exception或Error,都不会导致程序中断执行。
对象克隆
克隆就是对象的复制,在Object类中存在clone方法用于对象的clone:
protected Object clone() throws CloneNotSupportedException
这种操作有点类似C/C++中的拷贝构造。同时该方法本身使用了protected访问权限,这样当在不同的包产生对象时将无法调用Object类中的clone方法,因此就需要通过子类覆写clone方法(调用父类的clone方法),才可以正常完成克隆操作。
而在clone方法上抛出的错误为“CloneNotSupportedException”。这是因为不是所有的对象都可以被克隆,可以克隆的对象一般会实现Cloneable接口,以便实现克隆操作。
class A implements Cloneable {
private String name;
public A(String name) {
this.name = name;
}
String getName() {
return name;
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Demo {
public static void main(String[] args) throws Exception {
A a = new A("ABC");
System.out.println(a.getName());
A aa = (A)a.clone();
System.out.println(aa.getName());
}
}
执行结果为:
ABC
ABC
上面的代码中实现了Cloneable接口,同时覆写了clone方法,这样就能够调用clone方法,实现克隆操作。这里克隆出来的实例化对象和原对象占据不同的存储空间,不互相影响。