class Remember private constructor() {
private var data: ConcurrentMap<String, Any> = ConcurrentHashMap()
private fun <T> saveValue(key: String, value: T): Remember {
data[key] = value
return this
}
private fun <T> getValue(key: String, clazz: Class<T>): T? {
val value = data[key]
var castedObject: T? = null
//Failed here
if (clazz.isInstance(value)) {
castedObject = clazz.cast(value)
}
return castedObject
}
fun putInt(key: String, value: Int): Remember {
return saveValue(key, value)
}
fun getInt(key: String, fallback: Int): Int {
val value = getValue(key, Int::class.java)
return value ?: fallback
}
}
当我putInt(key, 123)
时,123
会自动退回到java.lang.Integer
。当我从Map
获得价值时,在这种情况下,如何将value
键入的Any
与Class<T>
进行比较,其中T为Int:class.java
?目前,clazz.isInstance(value)
始终失败。如果这个类是用Java编写的