昨天宪迟,寫B(tài)aseApplication時候,一些“靜態(tài)方法、屬性”都放在companion object(ps:kotlin 根本沒有靜態(tài)這個概念躲舌,而伴生對象本身是一個單例對象会通,kotlin的字節(jié)碼中可以看到)中口予,MyApplication繼承BaseApplication了
//基類
open class BaseApplication : MultiDexApplication() {
init {
initInstance()
}
private fun initInstance() {
instance = this
}
override fun onCreate() {
super.onCreate()
//instance = this
mainThreadHandler = Handler(Looper.getMainLooper())
mainThreadId = Process.myTid()
}
companion object {
lateinit var instance: BaseApplication
private var mainThreadHandler: Handler? = null
private var mainThreadId: Int? = 0
/** 上下文(Application) */
fun getContext(): Context {
return instance.applicationContext
}
/** 主線程Handler */
fun getMainHandler(): Handler {
return mainThreadHandler!!
}
/** 主線程Id */
fun getMainThreadId(): Int {
return mainThreadId!!
}
}
}
//子類
class MyApplication: BaseApplication()
如果你想子類調(diào)用BaseApplication中的“靜態(tài)方法”,如:
MyApplication.getContext() // wrong
發(fā)現(xiàn)只能用父類名.getContext()涕侈,說明 kotlin 的“靜態(tài)” 不能被子類繼承沪停,順便翻墻查了一下,然后裳涛,改造代碼:
//基類
open class BaseApplication : MultiDexApplication() {
init {
initInstance()
}
private fun initInstance() {
instance = this
}
override fun onCreate() {
super.onCreate()
//instance = this
mainThreadHandler = Handler(Looper.getMainLooper())
mainThreadId = Process.myTid()
}
companion object {
lateinit var instance: BaseApplication
private var mainThreadHandler: Handler? = null
private var mainThreadId: Int? = 0
/** 上下文(Application) */
fun getContext(): Context {
return instance.applicationContext
}
/** 主線程Handler */
fun getMainHandler(): Handler {
return mainThreadHandler!!
}
/** 主線程Id */
fun getMainThreadId(): Int {
return mainThreadId!!
}
}
open class BaseApplicationCompanion {
open fun getContext() : Context = BaseApplication.getContext()
open fun getMainHandler() : Handler = BaseApplication.getMainHandler()
open fun getMainThreadId() : Int = BaseApplication.getMainThreadId()
}
}
//子類
class MyApplication: BaseApplication() {
companion object : BaseApplicationCompanion()
}
ps:kotlin的伴生對象是可以繼承于另一個類
另外木张,一個(非單獨(dú))伴生對象不能繼承另外一個(非單獨(dú))伴生對象,如圖:
最后端三,貼出kotlin的字節(jié)碼(說明伴生對象就是一個靜態(tài)內(nèi)部類)