![](/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.