【问题标题】:Kotlin, how to retrieve field value via reflectionKotlin,如何通过反射检索字段值
【发布时间】:2017-07-10 15:32:36
【问题描述】:

所以我在几个 classes 中有数百个字段,我想在它们上编写一些方法,它们会自动 println 每个字段及其对应的值

目前我有这个:

inner class Version(val profile: Profile) {

    @JvmField val MINOR_VERSION = glGetInteger(GL_MINOR_VERSION)

    fun write(file: File? = null) {
        //file.printWriter().use { out -> out.pri }
        this::class.java.fields.forEach {
            println(it.isAccessible)
            println(it.getInt(it)) }
    }
}

但这就是我得到的:

false
Exception in thread "main" java.lang.IllegalArgumentException: Can not set final int field uno.caps.Caps$Version.MINOR_VERSION to java.lang.reflect.Field
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
    at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
    at sun.reflect.UnsafeQualifiedIntegerFieldAccessorImpl.getInt(UnsafeQualifiedIntegerFieldAccessorImpl.java:58)

有什么想法吗?

【问题讨论】:

标签: reflection kotlin


【解决方案1】:

除了使用 Java 字段和 Java 反射代码,您还可以使用 Kotlin 属性和 Kotlin 反射类:

class Reflector {
    val Foo = 1;

    fun printFields() {
        this::class.memberProperties.forEach {
            if (it.visibility == KVisibility.PUBLIC) {
                println(it.name)
                println(it.getter.call(this))
            }
        }
    }
}

【讨论】:

【解决方案2】:

您似乎将Field 变量it 作为参数getInt 传递,而参数应该是该字段所属的对象this

来自Field.getInt(Object obj) 的 Javadoc:

obj - the object to extract the int value from

也许这就是你的本意:

class Reflector {
    @JvmField val Foo = 1;

    fun printFields() {
        this.javaClass.fields.forEach {
            println(it.isAccessible)
            println(it.getInt(this))
        }
    }
}

fun main(args : Array<String>) {
    Reflector().printFields()
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 1970-01-01
    相关资源
    最近更新 更多