1. 前言
Native 关键字说明其修饰的方法是一个原生态方法,方法的实现不是在当前文件,而是在用其他语言实现的文件中,Java语言本身不能对操作系统底层进行访问和操作,但是可以通过Java Native Interface接口调用其他语言来实现对底层的访问
2. Object主要方法
-
private static native void registerNatives()
;- Object类中通过静态代码块的形式保证类加载的时候会调用该方法
-
public final native Class<?> getClass()
- 该方法返回Object的运行时class
-
public native int hashCode();
- 返回一个hash值
- 多次请求同一个对象的hashCode方法必须返回同一个int值
- 如果两个对象相等(equals方法),那么这两个对象的Hash值相等
- 两个对象如果基于equals方法不相同,这两个对象的hasCode方法结果可能相同。注意:两个不相同的对象产生相同的hash code可以提高hash table的效率
-
public boolean equals(Object obj) {return (this == obj);}
- 判断两个对象的引用是否相等
- 所有非空对象调用equals(null),返回结果都是false。 null 应该是独立的引用地址
-
protected native Object clone() throws CloneNotSupportedException;
- 深拷贝
- x.clone() != x
- x.clone().getClass() == x.getClass() 不一定为true
- 所有的Arrays都实现了该接口
- The method clone for class Object performs a specific cloning operation. First, if the class of this object does not implement the interface Cloneable, then a CloneNotSupportedException is thrown. Note that all arrays are considered to implement the interface Cloneable and that the return type of the clone method of an array type T[] is T[] where T is any reference or primitive type. Otherwise, this method creates a new instance of the class of this object and initializes all its fields with exactly the contents of the corresponding fields of this object, as if by assignment; the contents of the fields are not themselves cloned. Thus, this method performs a "shallow copy" of this object, not a "deep copy" operation.
- 上文表示:所有的Arrays都实现了Cloneable接口。在Arrays的实现中,Arrays通过调用clone方法返回并创建类型为T[]新对象。所以新创建的对象是“shallow copy" 而不是原对象的深拷贝。
6.public String toString() {return getClass().getName() + "@" +Integer.toHexString(hashCode());}
-
public final native void notify();
- 唤醒一个该类中被监控的等待线程
- 从等待队列中抽取一个线程被唤醒
- 被唤醒的线程不能执行直到现行线程释放锁
public final native void notifyAll();
public final native void wait(long timeout) throws InterruptedException;
protected void finalize() throws Throwable { }