简体   繁体   中英

Kotlin reflection on inbuilt classes

I am trying to read the "value" field of a String in Kotlin. I am not very familiar with reflection in Kotlin, so I can't get it to work. This is what I have:

var str: String = "Some string"

val field = String::class.java.getDeclaredField("value")
field.isAccessible = true

println(field) // This prints "private final char[] java.lang.String.value"

println(field.get(str)) // This prints [C@66d3c617

When trying to cast char[] to Array, I get this exception:

java.lang.ClassCastException: [C cannot be cast to [Ljava.lang.Character;

What am I doing wrong?

I am not sure what you are trying to achieve but you can try this.

val value = (field.get(str) as ByteArray).toString(Charset.defaultCharset())
println(value)

In my env, the field is a ByteArray so I casted it to a ByteArray and get a printable version. In your case, a simple CharArray should suffice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM