简体   繁体   English

Kotlin对内置类的反思

[英]Kotlin reflection on inbuilt classes

I am trying to read the "value" field of a String in Kotlin. 我正在尝试在Kotlin中读取String的“ value”字段。 I am not very familiar with reflection in Kotlin, so I can't get it to work. 我对Kotlin中的反射不太熟悉,因此无法正常工作。 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: 尝试将char []强制转换为Array时,出现以下异常:

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. 在我的环境中,该字段是ByteArray,因此我将其强制转换为ByteArray并获得了可打印的版本。 In your case, a simple CharArray should suffice. 在您的情况下,一个简单的CharArray就足够了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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