public class Object {
/**
* 就是对几个本地方法进行注册(也就是初始化java方法映射到C的方法)。
* 具体参考 https://blog.csdn.net/chenyi8888/article/details/7070367
*/
private static native void registerNatives();
static {
registerNatives();
}
/**
* 获取Class对象 ,经常在反射中使用
*/
public final native Class<?> getClass();
/**
* hashCode() 和 equals() 一起重写,用于比较对象
*/
public native int hashCode();
/**
* 比较对象,经常一起重写 hashCode() 和 equals()函数,
* 比如在Map中,用一个对象作为key,就要重写这两个方法
*/
public boolean equals(Object obj) {
return (this == obj);
}
/**
* 浅复制,类要实现 java.lang.Cloneable接口,不然会抛出CloneNotSupportedException
*/
protected native Object clone() throws CloneNotSupportedException;
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
/**
* 唤醒某个等待的线程
*/
public final native void notify();
/**
* 唤醒所有等待的线程
*/
public final native void notifyAll();
/**
* 线程等待,直到timeout
*/
public final native void wait(long timeout) throws InterruptedException;
public final void wait(long timeout, int nanos) throws InterruptedException {
if (timeout < 0) {
throw new IllegalArgumentException("timeout value is negative");
}
if (nanos < 0 || nanos > 999999) {
throw new IllegalArgumentException(
"nanosecond timeout value out of range");
}
if (nanos > 0) {
timeout++;
}
wait(timeout);
}
/**
* 只能用在synchronized块里,不然会报异常
* 一直等待,无超时时间
*/
public final void wait() throws InterruptedException {
wait(0);
}
/**
* 用于gc
*/
protected void finalize() throws Throwable { }
1. wait() 和 notice() 方法要用和synchronized一起使用,不然会抛出异常。
2. hashCode() 和 equals() 一起重写,用于比较对象。
3. clone() 方法提供 浅复制 ,不是每个属性都拷贝一份。比如出现如下的情况,调用clone()方法,id,name可以复制,而address属性都指向同一个对象。
Class Person {
int id;
String name;
Address address;
}
Class Address {
int addressId;
String addressName;
}
4.finalize() 方法,在gc第一次标记时,如果类中重写了这个方法,会调用这个方法。一次gc只调用一次。对象将放在F-Queue队列中,并且虚拟机会自动建立低优先级的Finalizer线程去执行这个方法。