Kotlin之Any(屌絲版)
官網靠譜中:http://kotlinlang.org/docs/reference/classes.html
0、All classes in Kotlin have a common superclass Any
, that is the default superclass for a class with no supertypes declared
在Kotlin所有類中,有一個公共的superclass,名字就叫:Any。 所有沒有顯式宣告基類的class,它的預設父類就是Any
class Cat{
}
比如Cat的超類就是Any
1、Note: Any
java.lang.Object
; in particular, it does not have any members other than equals()
, hashCode()
and toString()
. Please consult the Java interoperability section for more details
注意:Any不能等同於java.lang.Object;特別的是,Any除了equals()、hashCode()和toString()三個方法之外沒有任何其他成員。有關更多細節,請參考Java互操作性部分。
PS:我其實說明剛說,這Any跟Object好像,結果還真不是。雖然Object下也有hashCode、equals、toString方法
2、這篇文章只談Any撒,所以繼承部分不在這裡多寫了
3、http://kotlinlang.org/docs/reference/java-interop.html#object-methods我又去這裡看看Any的介紹,學習是學不完的啊,我服了自己了
4、When Java types are imported into Kotlin, all the references of the type java.lang.Object
Any
. Since Any
is not platform-specific, it only declares toString()
, hashCode()
and equals()
as its members, so to make other members of java.lang.Object
available, Kotlin uses extension functions.
將Java型別匯入Kotlin時,Java .lang.Object型別的所有引用將被轉換為Any。由於Any不是特定於平臺的,因此它只聲明瞭toString()、hashCode()和equals()作為它的成員方法,如果讓java.lang.Object的其他成員也可獲得的話,Kotlin就需要使用擴充套件函數了
5、注意坑來了
Methods wait()
and notify()
are not available on references of type Any
. Their usage is generally discouraged in favor of java.utl.concurrent
. If you really need to call these methods, you can cast to java.lang.Object
方法wait()和notify()在Any型別的引用上不可用。通常不鼓勵使用java.utl.concurrent。如果確實需要呼叫這些方法,可以將其轉換為java.lang.Object
(foo as java.lang.Object).wait() #看來as是強制轉換到每個class的意思撒
6、怎麼獲取Object中的getClass()
To retrieve the Java class of an object, use the java
extension property on a class reference:
若要檢索某個java class 的一個class物件,請在類引用上使用Java extension屬性:
val fooClass = foo::class.java # name :: class.java
還有一種辦法
The code above uses a bound class reference, which is supported since Kotlin 1.1. You can also use the javaClass
extension property
上面的程式碼使用繫結類引用,自Kotlin 1.1以來就支援這個類引用。您還可以使用javaClass擴充套件屬性
val fooClass = foo.javaClass
7、clone(),原有的Object下有clone()方法,在Kotlin下要怎麼做呢?
To override clone()
, your class needs to extend kotlin.Cloneable
去重寫clone方法,你的class需要擴充套件kotlin.Cloneable
class Example : Cloneable {
override fun clone(): Any { ... }
}
Do not forget about Effective Java, 3rd Edition, Item 13: Override clone judiciously.
這個Effective Java,可是牛書,第三版的第13條:顯式重寫clone方法
8、finalize()
To override finalize()
, all you need to do is simply declare it, without using the override keyword
要重寫finalize(),你只許喲簡單的宣告它,不用使用override關鍵字
class C {
protected fun finalize() {
// finalization logic
}
}
According to Java's rules, finalize()
must not be private.
根據java規則,finalize()方法不能是private的 (搞的我都想去官網擼一遍文件了,艹)
9、Calling Java code from Kotlin,Kotlin中肯定可以呼叫Java的程式碼嘛,混合開發牛哈