![](/img/trans.png)
[英]Android/Kotlin Crash on Start 4.1.2 - ExceptionInInitializerError
[英]ExceptionInInitializerError in Kotlin static initialization
我有一個 Kotlin 類,通過一個伴隨對象進行了一些靜態初始化。 但是當我嘗試運行我的應用程序時,我收到了一個 ExceptionInInitializerError 錯誤。
這是堆棧跟蹤:
Caused by: java.lang.ExceptionInInitializerError
at com.myapp.model.location.CountryList.getSelectableCountryList(CountryList.kt:19)
at com.myapp.ui.util.CountryStateSpinnerSet.<init>(CountryStateSpinnerSet.java:43)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
.
.
.
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object java.util.HashMap.get(java.lang.Object)' on a null object reference
at com.myapp.model.location.Country.<init>(Country.kt:31)
at com.myapp.model.location.Country.<init>(Country.kt:17)
at com.myapp.model.location.Country.<clinit>(Country.kt:19)
at com.myapp.model.location.CountryList.getSelectableCountryList(CountryList.kt:19)
at com.myapp.ui.util.CountryStateSpinnerSet.<init>(CountryStateSpinnerSet.java:43)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
.
.
.
還有我的兩個班級:
國家列表:
object CountryList {
val countryList: List<Country>
get() {
return listOf(
Country.UNITED_STATES, Country.CANADA
)
}
@JvmStatic val selectableCountryList: List<Country>
get() {
val countryList: MutableList<Country> = mutableListOf(Country.SELECT) <-- the ExceptionInInitializerError occurs on this line
countryList.addAll(countryList)
return countryList
}
}
國家:
data class Country(val name: String, val abbrev: String = ""): Parcelable {
companion object {
val SELECT = Country("Select Country")
val UNITED_STATES = Country("United States", "US")
val CANADA = Country("Canada", "CA")
private var countryStateMap: HashMap<Country, StateList> = hashMapOf(
UNITED_STATES to USStateList(),
CANADA to CanadaProvinceList()
)
}
@IgnoredOnParcel
val stateList: StateList = countryStateMap[this]!!
@IgnoredOnParcel
val selectableStateList: List<State>
get() = if (null != countryStateMap[this]) {
countryStateMap[this]!!.selectableStateList
}
else {
throw IllegalStateException("Can't retrieve selectable state list with country: $this")
}
override fun toString(): String {
val sb = StringBuilder()
if (abbrev.isNotEmpty()) {
sb.append(abbrev)
sb.append(" - ")
}
sb.append(name)
return sb.toString()
}
}
我是否以錯誤的順序初始化某些東西?
先感謝您。
我假設 Country.SELECT 在訪問時尚未初始化。 嘗試通過添加by lazy
來更改初始化順序,這會告訴 kotlin 稍后初始化 CountryList。
object CountryList {
val countryList: List<Country> by lazy {
...
CountryList 將在第一次實際使用時進行初始化。 屆時 Country.SELECT 可用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.