如何通过反射收集成员以便稍后作为参数传递

时间:2018-05-01 11:25:55

标签: reflection kotlin kotlin-reflect

所以,我正在研究一个概念,它自动写入ByteBuffer扩展Bufferizable

类的内容
abstract class Bufferizable {

    abstract val fieldOrder: Array<String>

    open fun size(): Int = TODO()

    var initialized = false

    open infix fun to(address: Long) {

        if (initialized) {

            addFunctions.forEach {  }

        } else {

            addFunctions = Array(fieldOrder.size) { null }
            members = Array(fieldOrder.size) { null }

            fieldOrder.forEachIndexed { i, field ->
                val member = this::class.declaredMemberProperties.find { it.name == field }!!
                addFunctions[i] = when (member.returnType) {
                    Mat4::class.defaultType.javaType -> WithAddress::addMat4
                    ...
                    else -> throw Error()
                } as BufferizableAddFunctionType
                members[i] = member.get(this) // error
            }

            initialized = true
        }
    }

    infix fun from(address: Long): Unit = TODO()

    var addFunctions = arrayOf<BufferizableAddFunctionType?>()
    var members = arrayOf<Any?>()
}

typealias BufferizableAddFunctionType = (Any) -> Unit

object WithAddress {

    var address = NULL
    var offset = 0

    fun addMat4(mat4: Mat4) {
        for (i in 0..3)
            for (j in 0..3) {
                memPutFloat(address + offset, mat4[i, j])
                offset += Float.BYTES
            }
    }
    ...
}

这个想法是宣告,例如,以下

object uboVS : Bufferizable() {

    var projectionMatrix = Mat4()
    var modelMatrix = Mat4()
    ...

    override val fieldOrder = arrayOf("projectionMatrix", "modelMatrix", "viewMatrix")
}

然后,只要第一次调用uboVS to address,它就会被初始化,然后按照指定的顺序将其内容写在本地地址。

但我遇到的唯一问题是收集成员以便稍后作为第i addFunction

的参数传递

因为编译器在这里抱怨:

members[i] = member.get(this)
  

错误:(328,37)Kotlin:Out-projection类型'KProperty1'禁止使用'public abstract fun get(receiver:T):R在kotlin.reflect.KProperty1中定义'

我该如何解决?

1 个答案:

答案 0 :(得分:1)

这是一个继承问题。您的反射调用this::class.declaredMemberProperties.find{ ... }会返回KProperty1<out Bufferizable, Any?>这意味着来自Bufferizable的属性(有关out的更多信息,请参阅declaration-site variance)。通过copiler不知道该属性属于哪个类,它不允许直接访问。要解决此问题,您必须访问getter函数:

members[i] = member.getter.call(this)

通过getter函数属于对象而不是反射api它遵循默认的继承行为并且可以被调用。