Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!