Mibac
Mibac

Reputation: 9448

Kotlin check parameter's type

When working with Java's reflection I can do something like this: method.getParameterTypes()[i] which gives me parameter's i type (Class).

How can I achieve this using Kotlin's KCallable? I've tried doing something like this: callable.parameters[i].type but the only thing I found was type.javaType but it returns Type which didn't help me at all. I also tried parameters[i].kind but that didn't help me at all.

How can I do Java's method.getParameterTypes() using Kotlin's KCallable?

Upvotes: 0

Views: 1328

Answers (1)

glee8e
glee8e

Reputation: 6419

If you are using Kotlin 1.1+,

1) You have kotlin-reflect, then you should use callable.parameters[i].type.jvmErasure.java.

2) You don't have kotlin-reflect, then go to 3)

If you are using older version, I strongly suggest you to port your code to 1.1. If for some reason you have to stick to the older one, go to 3),

3) You should first add this piece of code, which calculates the rawtype of a given java.lang.reflect.Type:

import java.lang.reflect.*

val Type.rawtype: Class<*>
    get() = when (this) {
        is Class<*> -> this
        is ParameterizedType -> rawType as Class<*>
        is GenericArrayType -> genericComponentType.rawtype.asArrayType()
        is TypeVariable<*> ->
            this.bounds[0]?.rawtype ?: Any::class.java // <--- A bug of smart cast here, forcing the use of "this."
        is WildcardType -> lowerBounds[0].rawtype
        else -> throw AssertionError("Unexpected type of Type: " + javaClass)
    }

fun Class<*>.asArrayType() = java.lang.reflect.Array.newInstance(this, 0).javaClass

then just call callable.parameters[i].type.javaType.rawtype.

Upvotes: 6

Related Questions