Reified T - getting Class<T>


#1

If I have a reified type T, how can I get a java.lang.Class for it. I can get a Kotlin KClass, and from that use Class.forName, but I imagine there’s an easier way?

final inline fun foo() :Class = Class.forName(T::class.qualifiedName) as Class

I need it for a library that requires a Class


#2

To obtain a Java class reference, use the .java property on a KClass instance.

https://kotlinlang.org/docs/reference/reflection.html#class-references


#3

T::class.java gives me an error in intellij, and T::class.javaClass returns a Class<KClass>

Try it online:

inline fun foo(): Unit {
val e = E::class.java
}

On-the-fly type checking
A multi-language Hello.kt
Warning:(2, 6) Variable ‘e’ is never used
Error:(2, 19) Type parameter bound for T in val kotlin.reflect.KClass.java: java.lang.Class
is not satisfied: inferred type E is not a subtype of kotlin.Any


#4
inline fun <reified T:Any> foo() = T::class.java

fun main(args: Array<String>) {
    println("Java class: " + foo<String>())
}

#5

Thanks for the reply. The key thing then is that the type parameter must be bound by Any.


#6

Yes,
and sounds like a bug…