Object and Any

Any

The Any class is a descendant of the Kotlin class structure, and each Kotlin inherits or indirectly inherits from the Any class

/** * The root of the Kotlin class hierarchy. Every Kotlin class has [Any] as a superclass. */ public open class Any { // Kotlin's function can have no function body. It is not an Abstract method, so subclasses need not be overridden. public open operator fun equals(other: Any?) : Boolean public open fun hashCode(): Int public open fun toString(): String }Copy the code

There are three open methods: equals, hashCode, and toString, where equals and hashCode must be changed simultaneously if needed.

Object

In Java, Object is also the root of the class structure, and each class inherits or indirectly inherits from Object

package java.lang;

public class Object {
	public Object() {
	}

	private static native void registerNatives();

	public final native Class<?> getClass();

	public native int hashCode();

	public boolean equals(Object var1) {
		return this == var1;
	}

	protected native Object clone() throws CloneNotSupportedException;

	public String toString() {
		return this.getClass().getName() + "@" + Integer.toHexString(this.hashCode());
	}

	public final native void notify();

	public final native void notifyAll();

	public final native void wait(long var1) throws InterruptedException;

	public final void wait(long var1, int var3) throws InterruptedException {
		if (var1 < 0L) {
			throw new IllegalArgumentException("timeout value is negative");
		} else if (var3 >= 0 && var3 <= 999999) {
			if (var3 > 0) {
				++var1;
			}

			this.wait(var1);
		} else {
			throw new IllegalArgumentException("nanosecond timeout value out of range");
		}
	}

	public final void wait() throws InterruptedException {
		this.wait(0L);
	}

	protected void finalize() throws Throwable {
	}

	static {
		registerNatives();
	}
}
Copy the code

There are a dozen more class methods in Java than there are in Kotlin. Seven of these local methods contain a static local method, and five can be overridden by subclasses

private static native void registerNatives();
static {
    registerNatives();
}
Copy the code

Static local methods are executed when the class is loaded. The purpose of this method is to load some native methods into the JVM through the class loader. When the Object class is loaded, it loads some native methods from methods into the JVM as follows:

Static JNINativeMethod methods[] = {{" hashCode ", "()I", (void *)&JVM_IHashCode}, {" wait ", "(J)V", (void *) & JVM_MonitorWait}, {" notify ", "V" (), (void *) & JVM_MonitorNotify}, {" notifyAll ", "V" (), (void *) & JVM_MonitorNotifyAll}, {" clone ", "() Ljava/lang/Object;" , (void *)&JVM_Clone}, };Copy the code
@Contract(pure = true) public final native Class<? > getClass();

Returns the Class object of the object’s Class. Class objects can be used in scenarios such as reflection.

public native int hashCode();

Returns the hash value of the object, used primarily for the hash tables of the HashMap.

A few things to note about hashing:

  • Equal objects must have the same hash code

  • Unequal objects must have different hash codes — wrong!

  • Objects with the same hash must be equal — wrong!

  • HashCode must be overridden when overriding equals

equals
 public boolean equals(Object var1) {
	return this == var1;
}
Copy the code

To determine whether a reference refers to the same address is to determine whether two references refer to the same object. String overrides this method to determine whether strings are equal.

protected native Object clone() throws CloneNotSupportedException;

This method is used for copying. Class implements the Cloneable interface to invoke this method need, otherwise throw CloneNotSupportedException.

Clone (super.clone()) :

public class TestOne implements Cloneable { @NonNull @Override protected TestOne clone() { TestOne obj = null; try { obj = (TestOne) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return obj; }}Copy the code

Deep copy

public class TestTwo implements Cloneable { public TestOne var; @NonNull @Override protected TestTwo clone() { TestTwo obj = null; try { obj = (TestTwo) super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } obj.var = obj.var.clone(); return obj; }}Copy the code
public String toString()

Returns a hexadecimal string of the class name and the hash value of the object. Subclasses are recommended to override this method.

Notify (), notifyAll(), wait() methods

Since version 1.0, every object in Java has an internal lock. If a method is declared with the synchronized keyword, the object’s lock protects the entire method. That is, to call this method, the thread must acquire an internal object lock.

Public synchronize void method(){method body} = public void method(){this.intrinsicLock.lock(); try{ method body } finally{ this.intrinsicLock.unlock(); }}Copy the code

From this example we can see the above methods in action.

public final native void notify();

Select a random thread that calls the WAIT method on this object and unblock it. This method can only be called in a synchronized method or block. If the current thread is not the object lock holders, the method throws an IllegalMonitorStateException anomalies.

public final native void notifyAll();

Unblock threads that call the WAIT method on this object. This method can only be called inside a synchronized method or a synchronized block. If the current thread is not the object lock holders, the method throws an IllegalMonitorStateException anomalies.

public final void wait() throws InterruptedException

Put the thread into a wait state until it is notified. This method can only be called in a synchronous method. If the current thread is not the object lock holders, the method throws an IllegalMonitorStateException anomalies.

public final void wait(long millis, int nanos) throws InterruptedException
public final native void wait(long millis) throws InterruptedException;

Parameters: millis milliseconds nanos nanoseconds < 1000 000 Causes the thread to wait until it is notified or a specified time has passed. These methods can only be called in a synchronous method. If the current thread is not a holder of the lock this method throws an IllegalMonitorStateException anomalies.

protected void finalize() throws Throwable

When an object in heap space is not referred to by a stackspace variable, the object is waiting to be reclaimed by Java.

The GC features:

  • When an object is no longer in use by the program, the garbage collector collects it
  • Garbage collection runs in the background, we can’t tell the garbage collector to collect resources right away, but we can tell it to collect resources as soon as possible (system.gc () and Runtime.geTruntime ().gc())).
  • When the garbage collector collects an object, it first calls the Finalize () method of the object
  • GC is mainly for heap memory
  • Disadvantages of the singleton pattern

Any is the same as Object

Any in Kotlin only exists at compile time, not at run time.

val any = Any()
println("any:$any ")
println("anyClass:${any.javaClass} ")

val obj = any as Object
synchronized(obj){
	obj.wait()
}
println("obj:$obj ")
println("obj:${any.`class`} ")

I/System.out: any:java.lang.Object@d12ebc1 
I/System.out: anyClass:class java.lang.Object 
I/System.out: obj:java.lang.Object@d12ebc1 
I/System.out: obj:class java.lang.Object 
Copy the code

As you can see from the above example, Any becomes Object at Runtime, and it is also possible to force Any to Object in Kotlin.

From Kolitn’s official documentation kotlinlang.org/docs/java-i… You can see that Object corresponds to Any

Kotlin specializes in a few Java types. These types are not loaded from Java as-is, but instead map to the corresponding Kotlin types. The mapping only takes effect at compile time; the runtime representation remains the same. Java primitive types map to corresponding Kotlin types (keeping platform types)

As you can see from the example above, obj can be mixed with any. If any is strong, you can use notify() and extend any, such as obj.apply {}.