Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
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?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

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.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda