- 经典面试题Object类有哪些方法?
- 今天在这里梳理记录下。
有哪些呢?
详细介绍下
可用看到基本都是native方法,得去看jvm的实现才能知道具体逻辑。这里就不具体展开了。
//注册本地方法,具体可以百度
private static native void registerNatives();
static {
registerNatives();
}
//返回Object对象的class
public final native Class<?> getClass();
//返回返回Object对象的hashcode
public native int hashCode();
//判断对象是否相等
public boolean equals(Object obj) {
return (this == obj);
}
//对象clone
protected native Object clone() throws CloneNotSupportedException;
//java.lang.Object@4b67cf4d 知道这是怎么来的了吧
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
//唤醒一个等待object的monitor对象锁的线程
public final native void notify();
//唤醒所有等待object的monitor对象锁的线程
public final native void notifyAll();
/**
Object wait(long timeout) 方法让当前线程处于等待(阻塞)状态,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过参数 timeout 设置的超时时间。
如果 timeout 参数为 0,则不会超时,会一直进行等待,类似于 wait() 方法。
当前线程必须是此对象的监视器所有者,否则还是会发生 IllegalMonitorStateException 异常。
如果当前线程在等待之前或在等待时被任何线程中断,则会抛出 InterruptedException 异常。
如果传递的参数不合法,则会抛出 IllegalArgumentException 异常。
**/
public final native void wait(long timeout) throws InterruptedException;
/**
Object wait(long timeout, int nanos) 方法让当前线程处于等待(阻塞)状态,直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法,或者超过参数 timeout 与 nanos 设置的超时时间。
该方法与 wait(long timeout) 方法类似,多了一个 nanos 参数,这个参数表示额外时间(以纳秒为单位,范围是 0-999999)。 所以超时的时间还需要加上 nanos 纳秒。
如果 timeout 与 nanos 参数都为 0,则不会超时,会一直进行等待,类似于 wait() 方法。
当前线程必须是此对象的监视器所有者,否则还是会发生 IllegalMonitorStateException 异常。
如果当前线程在等待之前或在等待时被任何线程中断,则会抛出 InterruptedException 异常。
如果传递的参数不合法或 nanos 不在 0-999999 范围内,则会抛出 IllegalArgumentException 异常。
**/
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);
}
/**
Object wait() 方法让当前线程进入等待状态。直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法。
当前线程必须是此对象的监视器所有者,否则还是会发生 IllegalMonitorStateException 异常。
如果当前线程在等待之前或在等待时被任何线程中断,则会抛出 InterruptedException 异常。
**/
public final void wait() throws InterruptedException {
wait(0);
}
/**
Object finalize() 方法用于实例被垃圾回收器回收的时触发的操作。
当 GC (垃圾回收器) 确定不存在对该对象的有更多引用时,对象的垃圾回收器就会调用这个方法。
************最好不要重写这个方法*************
**/
protected void finalize() throws Throwable { }