Kotlin,如何通过反射检索字段值

时间:2017-07-10 15:32:37

标签: reflection kotlin

所以我在几个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)

有什么想法吗?

2 个答案:

答案 0 :(得分:14)

您可以使用Kotlin属性和Kotlin反射类,而不是使用Java字段和Java反射代码:

class Reflector {
    val Foo = 1;

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

答案 1 :(得分:1)

您似乎将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()
}