检查该类是否实现了该接口。科特林

时间:2018-01-08 12:10:40

标签: reflection kotlin

我想检查SignalPayload的子类是否实现了接口IConvertible。我怎么能这样做?

sealed class SignalPayload {
    companion object {
        fun trueTypeInstance(type: KClass<SignalPayload>) : SignalPayload? {
          //  if (*** __ KClass<SignalPayload> implemented IConvertible ___  **) 
                ......

        }
    }
}
object Empty : SignalPayload()
data class BadData(val message: String = "BAD") : SignalPayload() {
    override fun toString(): String {
        return message
    }
}
data class payloadString(private var payload: String = "") : SignalPayload(), IConvertible
data class payloadInt(private var payload: Int = 0) : SignalPayload(), IConvertible
data class payloadFloat(private var payload: Float = 0F) : SignalPayload(), IConvertible
data class payloadBool(private var payload: Boolean = false) : SignalPayload(), IConvertible 

interface IConvertible {
    val asBool: Boolean
    val asInt: Int
    val asFloat: Float
    val asString: String
    fun setFromPayload(data: IConvertible)
}

我该怎么做?

UPD
我曾经想过用它 类SignalChannel知道所需的字段mPayload(通过属性val type: ???)。起初mPayload等于空

interface IArriving {
    fun onNewPayload(data: SignalPayload, sender: IArriving?)
}
interface IConvertible {
    val asBool: Boolean
    val asInt: Int
    val asFloat: Float
    val asString: String
    fun setFromPayload(data: IConvertible)
}

class SignalChannel(val idx: Int, val type: ???, val name: String = "") : IArriving {
var mPayload: SignalPayload = Empty

// when new data arriving - need converting for `type` and refresh field mPayload 
override fun onNewPayload(data: SignalPayload, sender: IArriving?) {
       if ( mPayload is Empty ) { 
           mPayload = SignalPayload.trueTypeInstance(type) // that's my problem
       }
       mPayload.setFromPayload(data)

    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用正确的泛型,以便将方法限制为SignalPayload IConverible的类型:

fun <T> trueTypeInstance(): SignalPayload? 
   where T : IConvertible, T : SignalPayload {
     TODO()
} 

这样称呼:

SignalPayload.trueTypeInstance<payloadString>() //OK
SignalPayload.trueTypeInstance<Empty>() //Fails
SignalPayload.trueTypeInstance<String>() //Fails

虽然不确定您的用例......