I was trying to get cast reflection field to Map, but it gives me this error:
java.lang.ClassCastException: java.lang.reflect.Field cannot be cast to java.util.Map
How do I fix this?
Minimal Reproducible Example:
open class Base {
var inherited: Map<String, String> = mapOf(Pair("testing", "testing"))
}
class Child: Base() {
var notInherited: Int = 100
}
fun main() {
val c = Child()
var inheritedMap: Map<String, String> = c.javaClass.superclass.getDeclaredField("inherited") as Map<String, String>
println(inheritedMap)
}
link to code playground: https://pl.kotl.in/xW8g4pNsX
CodePudding user response:
c.javaClass.superclass.getDeclaredField("inherited")
That represents the actual field. The global concept. Yeah, you got there via c
, but one you run c.javaClass
, you've 'left' the instance behind.
You need to ask the field object to go fetch you the value for any given instance. add .get(c)
at the end of all that, and voila.
Using reflection to access things you know the name of as you write the code is a bad measure - it should be used only if you've exhausted all other feasible options. You may want to doublecheck a few things, possibly go back a step and ask for advice on how to do whatever it is that made you think: I know! I'll use reflection! - There might be better answers.